我有两个MySQL表:
alerts
alerts_viewed
警报是一个包含警报基本信息的表,alerts_viewed
表包含有关已查看警报的信息(按用户ID和警报ID):
alerts_viewed
上的字段为:
基本上,我知道如果我只想从alerts_viewed
中具有相应行的警报中选择行,我可以进行INNER JOIN。我只是不知道如何做到另一个方向。
如何从alerts
表中选择alerts_viewed
表中没有相应行的所有行?
答案 0 :(得分:4)
使用LEFT JOIN
SELECT a.*
FROM alerts a
LEFT JOIN alerts_viewed b
ON a.alert_id = b.alert_id
WHERE b.alert_id IS NULL
答案 1 :(得分:1)
select * from alerts
where id not in (select alert_id from alert_viewed)
或
select a.* from alerts a
left outer join alert_viewed av on a.id = av.alert_id
where av.alert_id is null
答案 2 :(得分:0)
除了JW和Juergen的答案之外,我还想提出另一种方法
NOT EXISTS ,
select * from alerts aa
where not exists
(select alert_id
from alert_viewed av
where av.alert_id=aa.id
)