sql—选择所有字段满足条件的所有数据

xmd2e60i  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(335)

请帮我编写一个sql查询。有一个数据库(其中有更多的列,但我认为这并不重要)。如何获取所有卖家id,所有商店都关闭了,如果至少有一个商店打开或暂时关闭,那么它就不起作用。对于我在下面给出的数据,只应显示卖家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
nnt7mjpx

nnt7mjpx1#

可以使用聚合和 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)
                 );

相关问题