如何检查具有相同外键的记录是否具有特定值

时间:2015-08-19 17:58:32

标签: mysql

见下表:

id foreign_key_id event_type event_status
---------------------------------------
1        1            20         1
2        1            20         2
3        1            30         1
4        1            30         2
5        2            20         1
6        2            20         2
7        2            30         1

基本上,我想查询只返回外键,这些外键具有状态为1的事件类型为20的记录但不具有事件类型为30且状态为2的记录

在这种情况下,它应该返回fk 2。

2 个答案:

答案 0 :(得分:3)

您可以使用相关子查询。

SELECT DISTINCT foreign_key_id
FROM yourTable AS t1
WHERE t1.event_type = 20 and t1.event_status = 1
AND foreign_key_id NOT IN (
    SELECT foreign_key_id
    FROM yourTable AS t2
    WHERE t1.foreign_key_id = t2.foreign_key_id
    AND t2.event_type = 30 AND t2.event_status = 2)

DEMO

也可以使用LEFT JOIN

来完成
SELECT DISTINCT t1.foreign_key_id
FROM yourTable AS t1
LEFT JOIN yourTable AS t2
ON t1.foreign_key_id = t2.foreign_key_id
    AND t2.event_type = 30 AND t2.event_status = 2
WHERE t1.event_type = 20 and t1.event_status = 1
AND t2.id IS NULL

DEMO

答案 1 :(得分:0)

{{1}}

希望它有所帮助。