Sql 查找组合不存在的行
我需要查找SQL表中不存在特定组合的所有行。例如,考虑下表。Sql 查找组合不存在的行,sql,sql-server,Sql,Sql Server,我需要查找SQL表中不存在特定组合的所有行。例如,考虑下表。 ID Column_1 Column_2 1. ID1 ABC 2. ID1 XYZ 3. ID1 QWE 4. ID2 XYZ 5. ID2 QWE 6. ID3 XYZ 7. ID3 ABC 8. ID3 QWE 在上表中,我需要返回ID2,因为没有ID2,ABC组合。我目前正在做一段时间,如果表中的每个ID都存
ID Column_1 Column_2
1. ID1 ABC
2. ID1 XYZ
3. ID1 QWE
4. ID2 XYZ
5. ID2 QWE
6. ID3 XYZ
7. ID3 ABC
8. ID3 QWE
在上表中,我需要返回ID2,因为没有ID2,ABC组合。我目前正在做一段时间,如果表中的每个ID都存在,那么,有没有更有效的方法?这里的音量很大
更新:以下所有答案似乎都返回了预期值。一种方法比其他方法有优势吗 如果您只需要ID2,您可以使用group by并拥有:
如果您确实想要缺少的值,则查询会稍微复杂一些。可能需要not in和subselect
select distinct column_1
from my_table
where column_1 not in (select column_1 from my_table
where column_2 ='ABC');
您可以使用如下查询:
with ids (v1) as
(select distinct v1 from Mytable),
vals (v2) as
(select distinct v2 from Mytable),
allCombs as
(select v1, v2 from ids, vals)
select * from allCombs c
where not exists (select * from myTable t where c.v1 = t.v1 and c.v2 = t.v2);
如果您想要所有列_1中没有一个列表,您可以在一般情况下这样做
-- first make the list
with items_2_find as
(
SELECT 'ABC' as V
UNION ALL
SELECT 'XYZ' as V
UNION ALL
SELECT 'QWE' as V
)
-- left join and find missing
SELECT items_2_find.V
FROM items_2_find
LEFT JOIN aTable ON items_2_find.V = aTable.Column_2
WHERE aTable.Column_1 is null
我删除了不兼容的数据库标记。为您真正使用的数据库添加回标记。mysql或sql server???sql server。很抱歉
-- first make the list
with items_2_find as
(
SELECT 'ABC' as V
UNION ALL
SELECT 'XYZ' as V
UNION ALL
SELECT 'QWE' as V
)
-- left join and find missing
SELECT items_2_find.V
FROM items_2_find
LEFT JOIN aTable ON items_2_find.V = aTable.Column_2
WHERE aTable.Column_1 is null