我有两个基于 ID 号的关系 MySQL 表。我需要选择第一个表中与第二个表中的任何 ID 都不匹配的 ID 计数。这是我尝试过的:
SELECT COUNT(DISTINCT(ask_questions.id))
FROM ask_questions
INNER JOIN ask_answers ON ask_questions.id != ask_answers.question_id;
我认为使用“!=”会返回不匹配的结果,但返回的数字不正确。有更好的解决方案吗?
使用LEFT JOIN
,因为你想得到ID
在另一张桌子上至少没有匹配的东西。
SELECT COUNT(DISTINCT(ask_questions.id))
FROM ask_questions
LEFT JOIN ask_answers
ON ask_questions.id = ask_answers.question_id
WHERE ask_answers.question_id IS NULL
要进一步了解有关联接的更多信息,请访问以下链接:
另一种方法JOIN
是使用NOT EXISTS
SELECT COUNT(DISTINCT(id))
FROM ask_questions
WHERE NOT EXISTS
(
SELECT null
FROM ask_answers
WHERE ask_questions.id = ask_answers.question_id
)
利用NOT IN
SELECT COUNT(ask_questions.id)
FROM ask_questions
WHERE ask_questions.id NOT IN(SELECT question_id FROM ask_answers)
SELECT COUNT(DISTINCT(ask_questions.id))
FROM ask_questions
LEFT JOIN ask_answers ON ask_questions.id = ask_answers.question_id;
WHERE ask_answers.question_id IS NULL
左连接会让你得到ask_questions
即使他们没有ask_answers
。
没有的会有ask_answers
idnull
使用除了:
select count(*) from
(select id from questions
except
select id from ask_answers_questions) as subtable;
EXCEPT 将为您删除重复项。
--dmg
您想要外连接表,而不是内连接它们,然后选择第二个表中为空的列。
SELECT COUNT(DISTINCT(ask_questions.id))
FROM ask_questions
LEFT JOIN ask_answers ON ask_questions.id = ask_answers.question_id
WHERE ISNULL(ask_answers.id)