SQL - 多子句

标签 sql

我在尝试编写此查询时遇到问题。

示例表

表 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/

相关文章:

sql - 将 blob 从表导出到单个文件的最快方法

mysql - 游标在触发器内并更新表列

mysql - 按特定字符排序

带有 while 循环的 MySQL 查询

带分组的 SQL SELECT

sql - 如何在更新中将 bigint 转换为带时区的时间戳

sql - 将 SQL 查询与共享逻辑相结合

mysql - 无法在mysql上创建触发器

sql - 检索大量字段时如何在sql server中获得正确的计数?

sql - 如何为每个外键选择有限数量的行?