sql - 选择所有字段满足条件的所有数据
问题描述
请帮我编写一个 sql 查询。有一个数据库(里面有更多的列,但我认为这并不重要)。如何获取所有的seller_id,这里所有的店铺都关门了,如果至少有一个店铺开着或者暂时关门了,那就不行了。在我下面给出的数据的情况下,应该只显示seller_id 1 和4。提前致谢
seller_id | shop_id | shop_status
-------------------------------------
1 | 10 | close
2 | 11 | open
1 | 12 | close
2 | 13 | temporarily_close
3 | 14 | open
3 | 15 | close
4 | 16 | close
解决方案
您可以使用聚合和having
子句:
select seller_id
from t
group by seller_id
having min(shop_status) = max(shop_status) and min(shop_status) = 'close';
如果您有单独的卖家列表,那么not exists
可能会更快:
select s.*
from sellers s
where not exists (select 1
from t
where t.seller_id = s.seller_id and
t.shop_status <> 'close'
);
编辑:
如果shop_status
可以NULL
并且您想排除这些,那么您可以使用:
select seller_id
from t
group by seller_id
having min(shop_status) = max(shop_status) and
min(shop_status) = 'close' and
count(*) = count(shop_status);
和:
select s.*
from sellers s
where not exists (select 1
from t
where t.seller_id = s.seller_id and
(t.shop_status <> 'close' or t.shop_status is null)
);
推荐阅读
- android - Firebase 数据的变化不会得到更新
- android - 即使通过搜索包名称,我的应用程序已发布但未在 Playstore 中显示
- java - Wildfly 开始返回 UT000128: Remote peer closed connection before all data can be read
- django - 带有外键的模型上的Django分页
- if-statement - 将两个公式添加到一个单元格
- c++ - 有没有办法将最初作为字符串输入的数字字符数组复制到双向链表
- etcd - 错误“远程错误:tls:错误证书”,ServerName“”
- .net-core - 在 dotnet core 中配置 Azure AD 重定向
- html - 在 Jupyter 中使用 css 并排调整不同尺寸的图像
- java - Mongodb从特定月份获取记录