SQL检查记录之一是否与联接其他表不存在

时间:2018-11-17 22:18:54

标签: mysql sql

我尝试并搜索了解决方案,但没有发现任何问题。 我想制作一个SQL代码,检查另一个表中是否不存在一条记录。

SQL表:

Table name: ads
╔═══════╦═════════╗
║ ad_id ║ user_id ║
╠═══════╬═════════╣
║  1    ║ Jeff    ║
║  2    ║ Jeff    ║
╚═══════╩═════════╩

Second Table name: premium
╔═══════╦═════════╗
║ ad_id ║ user_id ║
╠═══════╬═════════╣
║  1    ║ Jeff    ║

如果user_id = Jeff在表Premium中没有记录,我想检查表Ads。在那种情况下,它几乎不能显示给我ad_id = 2

我尝试过的是:

SELECT * FROM ads 
INNER JOIN premium ON premium.ad_id = ads.id 
WHERE premium.user_id = 'Jeff'

3 个答案:

答案 0 :(得分:1)

我推荐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)上的索引,它还应该具有非常好的性能特征。

答案 1 :(得分:0)

您可以将关联子查询与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 Demo

答案 2 :(得分:0)

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`