我试着寻找解决办法,但什么也没找到。我想做一个sql代码来检查一条记录是否不存在于另一个表中。
sql表:
Table name: ads
╔═══════╦═════════╗
║ ad_id ║ user_id ║
╠═══════╬═════════╣
║ 1 ║ Jeff ║
║ 2 ║ Jeff ║
╚═══════╩═════════╩
Second Table name: premium
╔═══════╦═════════╗
║ ad_id ║ user_id ║
╠═══════╬═════════╣
║ 1 ║ Jeff ║
如果用户\u id=jeff在表premium中没有记录,我想检查表ads。在这种情况下,它几乎不应该告诉我ad\u id=2
我试过的是:
SELECT * FROM ads
INNER JOIN premium ON premium.ad_id = ads.id
WHERE premium.user_id = 'Jeff'
3条答案
按热度按时间2ekbmq321#
SELECT COUNT(a.
ad_id
) as cntFROM
premium
pINNER JOIN
ads
a ON a.user_id
= p.user_id
WHERE p.
user_id
= 'Jeff'GROUP BY p.
user_id
HAVING a.
ad_id
<> MIN(a.ad_id
)SELECT COUNT(a.
ad_id
) as cntFROM
premium
pINNER JOIN
ads
a ON a.user_id
= p.user_id
WHERE p.
user_id
= 'Jeff' AND a.ad_id
<> p.ad_id
ecbunoof2#
可以将相关子查询用于
NOT IN
```SELECT a.*
FROM ads a
WHERE a.ad_id NOT IN
( SELECT p.ad_id FROM premium p WHERE p.user_id = a.user_id and p.user_id = 'Jeff' );
lyfkaqu13#
我推荐
not exists
:这几乎是你的问题陈述的直接翻译。此外,在
premium(ad_id, user_id)
它还应该具有非常好的性能特性。