MySQL:使用SUM B加入(A,B),但在某些情况下B不存在行

时间:2015-02-02 02:55:41

标签: mysql join

  

大家好,我是stackoverflow新手。

     

如果我对提出这个问题有任何不妥之处,希望能够纠正我。   :)

我想制作一个提问系统,我在MySQL中有两个表。

  1. 表'问题' :它存储问题信息。

  2. 表' question_communication' :它存储经理和用户之间的问题回复。


  3. 以下是详细表格。

    question (Table)
        - question_id(INT)
        - uid(INT)
        - category(CHAR)
        - description(CHAR)
        - submit_time(DATETIME)
    

    question_communication (Table)
        - question_reply_id(INT)
        - question_id(INT)
        - uid(ID)
        - reply(CHAR)
        - time(DATETIME)
        - seen(TINYINT)           --- Other side has seen the message or not.(0 is not seen, 1 is seen)
    

    我希望查询结果包括:

    question_id, uid, category, description, submit_time, seen(=1), seen(=0)

    然后我尝试写下面的代码,

    SELECT T1.question_id, T1.uid, T1.category, T1.description, DATE_FORMAT(T1.submit_time, '%Y/%m/%d %H:%i') submit_time, SUM(T2.seen = 1) seen, SUM(T2.seen = 0) notseen
      FROM question T1, question_communication T2
      WHERE T1.question_id = T2.question_id
        AND T2.uid != (Here is attribute.)
      ORDER BY submit_time DESC
    

    WHERE T1.question_id = T2.question_id此行可能在一种情况下不起作用。

    T1 (question)有问题时,

    并且它在T2 (question_communication)中没有任何回复。

    所以T1.question_id = T2.question_id会导致SQL JOIN超出我的预期。


    我的问题摘要:

    1. 如何成功查询结果如:
    2. question_id, uid, category, description, submit_time, seen(=1), seen(=0)

      1. 如果T1中有问题,但T2没有回复。 seen(=1)seen(=0)必须为zero

      2. 谢谢大家:)


        来自@Gordon Linoff的回答,我添加了COALESCE():

        SELECT T1.question_id, T1.uid, T1.category, T1.description,
               DATE_FORMAT(T1.submit_time, '%Y/%m/%d %H:%i') as submit_time,
               COALESCE(SUM(T2.seen = 1), 0) as seen, COALESCE(SUM(T2.seen = 0), 0) as notseen
        FROM question T1 LEFT JOIN
             question_communication T2
             ON T1.question_id = T2.question_id 
        GROUP BY T1.question_id, T1.uid, T1.category, T1.description,
                 DATE_FORMAT(T1.submit_time, '%Y/%m/%d %H:%i') 
        ORDER BY submit_time DESC;
        

1 个答案:

答案 0 :(得分:4)

我认为你只需要一个left join。实际上,您应该始终使用显式join语法。您的查询还需要group by。因此,查询看起来像:

SELECT T1.question_id, T1.uid, T1.category, T1.description,
       DATE_FORMAT(T1.submit_time, '%Y/%m/%d %H:%i') as submit_time,
       SUM(T2.seen = 1) as seen, SUM(T2.seen = 0) as notseen
FROM question T1 LEFT JOIN
     question_communication T2
     ON T1.question_id = T2.question_id 
GROUP BY T1.question_id, T1.uid, T1.category, T1.description,
         DATE_FORMAT(T1.submit_time, '%Y/%m/%d %H:%i') 
ORDER BY submit_time DESC;

我不知道T2.uid != (Here is attribute.)应该做什么。如果您在T2上有过滤条件,请将其放在ON子句中。