见下表:
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
基本上,我想查询仅返回具有事件类型 20 和状态 1 的记录但没有事件类型 30 和状态 2 的记录的外键
在这种情况下,它应该返回 fk 2。
最佳答案
您可以使用相关子查询。
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)
它也可以通过 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
关于mysql - 如何检查具有相同外键的记录是否具有特定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32102483/