从表中选择具有相同外键的所有其他记录具有特定值的记录

时间:2012-01-18 04:09:03

标签: sql tsql

我有下表

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

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

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

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

然后我唯一会回来的item_id是2。

3 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:1)

select distinct item_id
from ItemStatus
where status = 'A'
and item_id not in
(
    select item_id
    from ItemStatus
    where status != 'A'
    or status is null
)

会导致item_ids列表显示为A至少一次,并且从不显示为其他任何内容

答案 2 :(得分:1)

这样的事情应该有效:

SELECT DISTINCT item_id
FROM your_table t1
WHERE
    NOT EXISTS (
        SELECT *
        FROM your_table t2
        WHERE t1.item_id = t2.item_id AND t2.status <> 'A'
    )

用简单的英语:选择没有状态与“A”不同的行的每个item_id

---编辑---

Shark's idea的变体:

SELECT item_id
FROM your_table
GROUP BY item_id
HAVING min(status) = 'A' AND max(status) = 'A'

如果您在{item_id,status}上有索引,则DBMS有可能非常好地进行优化。这是SQL Server执行计划:

enter image description here

相关问题