sql检查其中一条记录是否不存在,并连接其他表

zazmityj  于 2021-06-19  发布在  Mysql
关注(0)|答案(3)|浏览(324)

我试着寻找解决办法,但什么也没找到。我想做一个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'
2ekbmq32

2ekbmq321#

SELECT p.`ad_id` as ad_id, p.`user_id` as user_id
FROM `premium` p 
INNER 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`)
``` `MIN(a.ad_id)` 必须用条件替换要从表中选择的记录 `ads` 等等。如果你想要唱片 `Check if one of a records is not existing in another table` 所以

SELECT COUNT(a.ad_id) as cnt
FROM premium p
INNER 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)

所以,如果 `cnt > 0` 它意味着什么记录存在!
如果你在一个公司里有很强的关系 `p.ad_id === a.ad_id` :

SELECT COUNT(a.ad_id) as cnt
FROM premium p
INNER JOIN ads a ON a.user_id = p.user_id
WHERE p.user_id = 'Jeff' AND a.ad_id <> p.ad_id

ecbunoof

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' );

sql fiddle演示
lyfkaqu1

lyfkaqu13#

我推荐 not exists :

select a.*
from ads a
where not exists (select 1
                  from premium p
                  where p.ad_id = a.ad_id and p.user_id = a.user_id
                 );

这几乎是你的问题陈述的直接翻译。此外,在 premium(ad_id, user_id) 它还应该具有非常好的性能特性。

相关问题