SQLite3使用LEFT JOIN和UNION模拟RIGHT OUTER JOIN
技术问答
233 人阅读
|
0 人回复
|
2023-09-14
|
我有以下选择句子,在这里我需要对表tbTasks每个任务中的求和,按表tbProjects中的projectId以获得类似的记录:
$ j# Q0 J* z2 K: q6 Q1 a( yProjectID = 1,ProjectName = 'My Project',TotalTime = 300 //查询如下:
$ A8 l# c' n- `% ]/ V. L6 k; v# tSELECT tbTasks.projectId, SUM(tbTasks.taskTime) AS totalTime, tbProjects.projectName FROM tbTasks INNER JOIN tbProjects ON tbTasks.projectId = tbProjects.projectId GROUP BY tbTasks.projectId ORDER BY tbProjects.created DESC这可以正常工作和执行,但有一个问题。如果一个项目没有与之相关的任务,那么我根本没有任何记录(我想从中得到它)projectId,projectName和totalTime的0或NULL)。因此,为了正确连接表tbProjects,SQLite3迫使我绕行。$ ~% ^$ N) ]- N% I3 V% Z
SELECT tbTasks.projectId, SUM(tbTasks.taskTime) AS totalTime, tbProjects.projectName FROM tbTasks LEFT OUTER JOIN tbProjects ON tbTasks.projectId = tbProjects.projectId GROUP BY tbTasks.projectId UNION SELECT tbProjects.projectId, SUM(tbTasks.taskTime) AS totalTime, tbProjects.projectName FROM tbProjects LEFT OUTER JOIN tbTasks ON tbProjects.projectId = tbTasks.projectId GROUP BY tbTasks.projectId ORDER BY tbProjects.created DESC只是这不起作用,我得到了一个SQL语法错误。我做错了什么?有没有更好的方法来实现我的目标? Q( ?$ P* P$ m% P/ `+ B
% k9 s) S" A" [2 Q d 解决方案:
5 o9 c9 ^! e, ]# M; a 即使SQLite尚未实现 RIGHT OUTER或FULLOUTER,它 也确实 具有LEFT OUTER JOIN,它应该做你想做的事。tbProjects在左边。8 e1 S0 N( ^/ ?% W1 u5 O: M7 ~
SELECT tbProjects.projectId, COALESCE(SUM(tbTasks.taskTime),0) AS totalTime, tbProjects.projectName FROM tbProjects LEFT OUTER JOIN tbTasks ON tbProjects.projectId = tbTasks.projectIdGROUP BY tbProjects.projectId ORDER BY tbProjects.created DESC您可以NULLS进入totalTime使用无任务的项目COALESCE()替换null的调用0。 |
|
|
|
|
|