Mysql - 右连接未检索到正确的数据

Mysql - Right join not retrieving correct data

我按开始时间和结束时间将用户 activity 存储在 table 中,现在我想从我的主题 table 中获取所有记录并从日志 table.

这是我的主题table

这是我的日志table

我想要这样的输出

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

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

您可以尝试将 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

您应该移动 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

在 where 条件中使用右连接列作为内部连接 ​​

这个怎么样?

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;

I changed to LEFT JOIN and TIMEDIFF instead because I couldn't get TIMESTAMPDIFF working on my side.