我在尝试编写此查询时遇到问题。
示例表
表 1
:
ID | Type
--------------------
111 | beer
111 | Wine
222 | Wine
333 | Soda
我想查询那些买了酒没买啤酒的。
我在
select ID
from table1
where type <>'beer'
and type = 'wine'
这是行不通的。有什么想法吗?
最佳答案
您正在查找表中类型不是啤酒而是 Wine 的记录。这不是你想要的。您应该查找存在或不存在记录的 ID。
通常你会关联一个 persons 表:
select *
from persons
where id in (select id from table1 where type = 'wine')
and id not in (select id from table1 where type = 'beer');
或存在
select *
from persons
where exists (select * from table1 where id = persons.id and type = 'wine')
and not exists (select * from table1 where id = persons.id and type = 'beer');
如果没有 persons 表,您可以简单地选择 ID:
select id
from table1 wine_buyers
where type = 'wine'
and not exists (select * from table1 where id = wine_buyers.id and type = 'beer');
或
select id
from table1
where type = 'wine'
and id not in (select id from table1 where type = 'beer');
一些 dbms 提供设置方法:
select id from table1 where type = 'wine'
minus
select id from table1 where type = 'beer';
编辑:只是觉得我应该添加一种只扫描表格一次的方法。你可以为每个 id 创建一个 Wine 和啤酒的标志:
select id
from table1
group by id
having max(case when type = 'wine' then 1 else 0 end) = 1
and max(case when type = 'beer' then 1 else 0 end) = 0;
关于SQL - 多子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22574889/