给定表:
+---+-------+------+---+
|id | attr | fker |did|
+---+-------+------+---+
|1 | attr1 | 5 | 1|
|2 | attr1 | 17 | 1|
|3 | attr1 | 3 | 2|
|4 | attr2 | 31 | 2|
|5 | attr2 | 7 | 2|
|6 | attr2 | 6 | 2|
|7 | attr3 | NULL | 1|
|8 | attr3 | NULL | 2|
|9 | attr3 | NULL | 1|
|10 | attr4 | NULL | 1|
|11 | attr4 | NULL | 1|
|12 | attr4 | NULL | 1|
+---+-------+------+---+
我需要一个 SQL 查询来列出所有且仅列出所有 fker=NULL
and did=1
在这个例子中,
- 只有 attr4 满足这个条件,因为
- attr1 没有 fker=NULL,
- attr2 没有它的所有 did=1(实际上没有),
- attr3 没有所有的 fekr=NULL(即使有,它也有 did=2)。
换句话说,查询的结果集中应该只有“attr4”。
在 http://sqlfiddle.com 上使用以下示例:
CREATE TABLE IF NOT EXISTS `ha_example` (
`id` int(6) unsigned NOT NULL,
`attr` varchar(200) NOT NULL,
`fker` int null,
`did` int(3) unsigned NOT NULL,
PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;
INSERT INTO `ha_example` (`id`, `attr`, `fker`, `did`) VALUES
('1', 'attr1', '5', '1'),
('2', 'attr1', '17', '1'),
('3', 'attr1', '3', '2'),
('4', 'attr2', '31', '2'),
('5', 'attr2', '7', '2'),
('6', 'attr2', '6', '2'),
('7', 'attr3', NULL, '1'),
('8', 'attr3', NULL, '2'),
('9', 'attr3', NULL, '1'),
('10', 'attr4', NULL, '1'),
('11', 'attr4', NULL, '1'),
('12', 'attr4', NULL, '1');
我尝试了这个 SQL(在类似问题 here 的帮助下——相似但不完全相同):
SELECT COUNT(fker), SUM(CASE WHEN did = 1 THEN 1 ELSE 0 END), attr, he.*
FROM ha_example he
group by attr,did
HAVING COUNT(fker) = SUM(CASE WHEN did = 1 THEN 1 ELSE 0 END)
但我无法计算出一个 attr
的所有行的总计数,如果不放弃两个字段而不是一个字段的组。
我该如何实现?
最佳答案
您可以使用group by
和having
:
select attr
from ha_example he
gropu by attr
having count(fker) = 0 and max(did) = min(did) and max(did) = 1;
您还可以使用:
having sum( fker is not null or did <> 1 ) = 0
或者如果您愿意:
having sum( not (fker is null and did = 1) ) = 0
关于mysql - SQL 查询查找一组行,其中一个字段中的所有行都具有特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67058301/