我到处搜索但找不到答案。所以问题正确。
假设我有一个这样的表
table1
+------+--------+
| id | attr |
+------+--------+
| 1 | weight |
| 1 | width |
| 1 | length |
| 2 | width |
| 2 | length |
+------+--------+
我想查询以获取缺少attr的行的id。 在这种情况下,id 2。
要检查的attr可以是一个列表,例如( '体重', '宽度', '长度', '高度') 或选择例如SELECT DISTINCT attr FROM table1 WHERE id = 1。
我尝试过NOT IN和NOT EXISTS,但我只能获得0或所有结果。
SELECT id FROM table1
WHERE attr NOT IN ('weight', 'length', 'width','height')
和
SELECT id
FROM table1 t1
WHERE NOT EXISTS
(
SELECT 1
FROM table1 t2
WHERE t2.name NOT IN('weight', 'length', 'width','height')
)
修改
如果表格像
+------+--------+
| id | attr |
+------+--------+
| 1 | weight |
| 1 | width |
| 1 | length |
| 1 | height |
| 2 | width |
| 2 | length |
| 2 | other |
+------+--------+
我如何获得以下内容?即。行id的缺失attr(我在评论中解释的id只是别名而不是主键id)
+------+--------+
| id | attr |
+------+--------+
| 2 | width |
| 2 | length |
+------+--------+
答案 0 :(得分:0)
有几种方法可以做到这一点。这是使用聚合的一个:
select id
from table1
where attr in ('weight','length','width')
group by id
having count(distinct attr) <> 3
答案 1 :(得分:0)
您可以将group by
与having
子句一起使用,例如:
select id
from table
where attr in ('weight','width','length')
group by id
having count(distinct(attr)) < 3