SQLite3使用左连接和并集模拟右外连接

14ifxucb  于 2023-03-03  发布在  SQLite
关注(0)|答案(2)|浏览(258)

我有下面的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和totalTime的0或NULL)。因此,为了在表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语法错误。我做错了什么?有没有更好的方法来实现我的目标?

bqujaahr

bqujaahr1#

即使SQLite hasn't implementedRIGHT OUTERFULL OUTER,它确实LEFT OUTER JOIN,这应该可以满足您的需要。

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

对于没有任何任务的项目,可以在totalTime中获得NULLS,并且对COALESCE()的调用将null替换为0

mccptt67

mccptt672#

version 3.39.0开始,SQLite支持右外连接和全外连接:

SELECT *
FROM t1 RIGHT JOIN t2
  ON t1.id = t2.id;

感谢Lukasz Szozda提供的their answer

相关问题