如何选择一个表列的COUNT,其中另一个表列中没有匹配项

时间:2013-06-03 01:15:43

标签: mysql sql

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

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

5 个答案:

答案 0 :(得分: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
        )

答案 1 :(得分:1)

使用NOT IN

SELECT COUNT(ask_questions.id)
FROM ask_questions
WHERE ask_questions.id NOT IN(SELECT question_id FROM ask_answers)

答案 2 :(得分: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_answers的用户将拥有ID null

答案 3 :(得分:0)

使用除外:

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

EXCEPT将删除重复项。

- DMG

答案 4 :(得分:0)

您希望外连接表,而不是内连接它们,并选择第二个表中为null的列。

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)