SQLite3使用LEFT JOIN和UNION模拟RIGHT OUTER JOIN

时间:2012-02-05 04:57:17

标签: sql sqlite group-by union full-outer-join

我有以下select语句,我需要从表tbTasks中对每个任务求和,并通过表tbProjects中的projectId对它们进行分组,以获得如下记录:

ProjectID = 1, ProjectName = 'My Project', TotalTime = 300 //<--sum of each task time

查询如下所示:

SELECT 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和0或NULL的totalTime)。所以,为了正确加入表格,tbProjects SQLite3迫使我以圆形方式进行。

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语法错误。我究竟做错了什么?有没有更好的方法来实现我的目标?

1 个答案:

答案 0 :(得分:12)

即使SQLite hasn't implemented RIGHT OUTERFULL OUTER确实也有LEFT OUTER JOIN,这应该是你想要的。只需要tbProjects在左边。

SELECT tbProjects.projectId, 
       COALESCE(SUM(tbTasks.taskTime), 0) AS totalTime, 
       tbProjects.projectName 
FROM tbProjects
    LEFT OUTER JOIN tbTasks ON tbProjects.projectId = tbTasks.projectId
GROUP BY tbProjects.projectId 
ORDER BY tbProjects.created DESC

对于没有任何任务的项目,您在NULLS获得totalTime,并且对COALESCE()的调用会将0替换为空。