sql - 选择仅订购特定会议而不订购其他会议的客户
问题描述
假设我们有一个客户表和一个订单表,它们像这样链接在一起:client.id = order.client_id。订单表条目包含已购买的产品 ID。产品表条目包含购买此产品的会议 ID。
如何从特定会议列表中选择仅购买产品的客户?
我可以用一个 PHP 脚本来解决这个问题,发出多个请求,重新排列数据,但这并不好玩。
到目前为止我试过这个:
select
o.client_id,
array_agg(p.conference_id) as conference_ids
from product as p
left join order as o
on o.id = p.order_id
where
p.conference_id = any('{ 46545, 46543 }'::int[])
但这并没有奏效,因为它选择的客户不仅来自这些会议,而且还来自其他会议。
编辑:固定 sql 在语法上是正确的
解决方案
在不使用数组的情况下解决此问题的一种方法是:
select client.id
from product as p
left join order as o on o.id = p.order_id
group by client.id
having count(*) filter(where p.conference_id not in (46545, 46543)) = 0;
如果您还想断言上述两个会议也都参加了(即都参加了,但没有其他人参加),您可以在该子句中添加另一个断言HAVING
:
select client.id
from product as p
left join order as o on o.id = p.order_id
group by client.id
having count(*) filter(where p.conference_id not in (46545, 46543)) = 0 and
min(p.conference_id) <> max(p.conference_id);
推荐阅读
- java - java多线程执行器从不关闭线程
- python - PyQt Signal位置参数消失
- flutter - 暂时禁用文本字段时保持键盘打开
- javascript - 单击时如何在新的浏览器选项卡中打开下载链接并在文件下载链接出现之前在该选项卡上设置倒计时
- azure - Azure 管道输出错误 CS0117:“Resource.Id”不包含“XXXid”的定义(Xamarin Android)
- java - GraphQL 错误:需要一个名为“FileUpload”的用户定义的 GraphQL 标量类型,但没有找到
- android - 如何使 Android 通知“持久”?
- c# - Asp Net Core (2.1) WebApp - API 和 Web 界面的身份验证
- react-native - Redux 远程开发工具:Chrome 检查器选项卡而不是单独的窗口
- sql - SQL:添加外键失败