3

我有两个基于 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;

我认为使用“!=”会返回不匹配的结果,但返回的数字不正确。有更好的解决方案吗?

4

5 回答 5

4

使用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
        )
于 2013-06-03T01:20:22.453 回答
1

利用NOT IN

SELECT COUNT(ask_questions.id)
FROM ask_questions
WHERE ask_questions.id NOT IN(SELECT question_id FROM ask_answers)
于 2013-06-03T01:22:26.427 回答
0
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_answersidnull

于 2013-06-03T01:20:14.700 回答
0

使用除了:

select count(*) from 
    (select id from questions 
     except 
     select id from ask_answers_questions) as subtable;

EXCEPT 将为您删除重复项。

--dmg

于 2013-06-03T01:20:55.813 回答
0

您想要外连接表,而不是内连接它们,然后选择第二个表中为空的列。

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)
于 2013-06-03T01:21:03.593 回答