从表中选择记录,其中具有相同外键的所有其他记录都具有特定值 [英] Select records from a table where all other records with same foreign key have a certain value

查看:21
本文介绍了从表中选择记录,其中具有相同外键的所有其他记录都具有特定值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个下表

ItemStatus
----------
id
item_id
status

我想选择所有 item_id,其中表中具有该 item_id 的每条记录的状态为 A.

I want to select all item_ids where the status for every record with that item_id in the table is A.

例如,如果记录是这样的:

For example if the records were like this:

id    item_id    status
-----------------------
1        1          A
2        1          B
3        2          A
4        2          A
5        3          B

那么我唯一能得到的 item_id 是 2.

Then the only item_id I would get back is 2.

推荐答案

    select item_id
    from YourTable
    group by item_id
    having sum(case when status='A' then 1 else 0 end) = count(1)

这篇关于从表中选择记录,其中具有相同外键的所有其他记录都具有特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆