我到处搜索,但找不到答案。所以问题就对了。
假设我有一张这样的 table
table1
+------+--------+
| id | attr |
+------+--------+
| 1 | weight |
| 1 | width |
| 1 | length |
| 2 | width |
| 2 | length |
+------+--------+
我想要一个查询来获取缺少属性的行的 ID。 在本例中,id 为 2。
要检查的属性可以是一个列表,例如('重量','宽度','长度','高度') 或选择例如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 |
+------+--------+
如何获得以下内容? IE。行 ID 的缺失属性(我在评论中解释的 ID 只是一个别名,而不是主键 ID)
+------+--------+
| id | attr |
+------+--------+
| 2 | width |
| 2 | length |
+------+--------+
最佳答案
有几种方法可以做到这一点。这是一个使用聚合的方法:
select id
from table1
where attr in ('weight','length','width')
group by id
having count(distinct attr) <> 3
关于MySQL select id 其中至少有一个值不在列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36167566/