SQL - 多个子句

时间:2014-03-22 07:41:50

标签: sql

我正在尝试编写此查询的问题。

示例表

Table1

ID   | Type  
--------------------
111  | beer  
111  | Wine  
222  | Wine  
333  | Soda  

我试图询问那些买葡萄酒但没有买啤酒的人。

我在

select ID
from table1
where type <>'beer' 
and   type = 'wine'

哪个不起作用。有什么想法吗?

3 个答案:

答案 0 :(得分:3)

您正在寻找表中不是啤酒而是葡萄酒的记录。这不是你想要的。您应该查找存在或不存在记录的ID。

通常你会有一个人员表:

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');

如果没有人员表,您可以简单地选择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提供了set方法:

select id from table1 where type = 'wine'
minus
select id from table1 where type = 'beer';
编辑:我想应该添加一种只扫描一次表格的方法。你可以为每个身份创造葡萄酒和啤酒的旗帜:

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;

答案 1 :(得分:2)

SELECT id 
FROM table1
WHERE type = 'wine' 
AND id NOT IN
    (SELECT id 
    FROM table1
    WHERE type = 'beer');

嵌套查询选择购买啤酒的人。外部查询选择那些已购买葡萄酒但没有购买啤酒的人员列表中的ID。

答案 2 :(得分:1)

Select ID
from table1 as t1
left join tabel1 as t2 on t1.id=t2.id
    and t2.type ='beer'
where t1.type = 'wine'
and t2.id is null