MySQL-右联接未检索正确的数据

时间:2019-01-14 07:02:53

标签: mysql outer-join

我正在按开始时间和结束时间将用户活动存储在表中,现在我想从主题表中获取所有记录,并从日志表中获取匹配的记录。

这是我的主题表

enter image description here

这是我的日志表

enter image description here

我想要这样的输出

enter image description here

我尝试使用一些代码,但是仅与日志表匹配的记录作为记录返回,这是我尝试过的。任何帮助都是可观的。

SELECT SUM(TIMESTAMPDIFF(MINUTE, A.start_time, A.end_time)) AS prep_time,
                B.subject_name,
                A.subject_id
            FROM prep_learn_log A
            RIGHT JOIN prep_subject B ON A.subject_id = B.subject_id 
                AND B.active = 'Y'
            WHERE A.user_id = '1' GROUP BY A.subject_id

3 个答案:

答案 0 :(得分:1)

您可以通过将A.user_id = '1'放在On Clause中来尝试以下操作

SELECT SUM(TIMESTAMPDIFF(MINUTE, A.start_time, A.end_time)) AS prep_time,
       B.subject_name,
       A.subject_id
       FROM prep_learn_log A
       RIGHT JOIN prep_subject B ON A.subject_id = B.subject_id 
       AND B.active = 'Y' and A.user_id = '1' 
       GROUP BY A.subject_id,B.subject_name

答案 1 :(得分:1)

您应该在ON子句中移动where条件

SELECT SUM(TIMESTAMPDIFF(MINUTE, A.start_time, A.end_time)) AS prep_time,
            B.subject_name,
            A.subject_id
        FROM prep_learn_log A
        RIGHT JOIN prep_subject B ON A.subject_id = B.subject_id 
            AND B.active = 'Y' AND A.user_id = '1' 
 GROUP BY A.subject_id

在条件用作内部联接的情况下使用右联接列

答案 2 :(得分:0)

这怎么样?

  

SELECT IFNULL(SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(b.end_time,b.start_time)))),"00:00:00") AS prep_time, a.subject_name,a.subject_id FROM prep_subject a LEFT JOIN prep_learn_log b ON a.subject_id = b.subject_id AND a.active = 'Y' GROUP BY a.subject_id ORDER BY a.subject_id;

     

我改为使用LEFT JOIN和TIMEDIFF,因为我无法让TIMESTAMPDIFF发挥作用。