简体   繁体   English

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

[英]SQLite3 Simulate RIGHT OUTER JOIN with LEFT JOINs and UNION

I have the following select statement where I need to sum each task from table tbTasks and group them by projectId from table tbProjects in order to get a record like this: 我有以下select语句,我需要从表tbTasks中对每个任务求和,并通过表tbProjects中的projectId对它们进行分组,以获得如下记录:

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

The query looks like this: 查询如下所示:

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

This works and executes fine but with one problem, if a project has no task associated with it, then I get no record back at all (where I want to get projectId, projectName, and 0 or NULL for totalTime). 这工作并执行正常但有一个问题,如果一个项目没有与之关联的任务,那么我根本没有得到任何记录(我想获得projectId,projectName和0或NULL的totalTime)。 So, in order to right join on the table tbProjects SQLite3 forces me to do it in a round-about way. 因此,为了正确加入表格,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

Only this does not work, I get an SQL syntax error. 只有这不起作用,我得到一个SQL语法错误。 What am I doing wrong? 我究竟做错了什么? Is there a better way to achieve my goal? 有没有更好的方法来实现我的目标?

Even though SQLite hasn't implemented RIGHT OUTER or FULL OUTER , it does have LEFT OUTER JOIN , which should do what you'd like. 尽管SQLite 没有实现 RIGHT OUTERFULL OUTER ,但它确实LEFT OUTER JOIN ,它应该按照您的意愿执行。 Just have tbProjects be on the left. 只需将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

You get NULLS in totalTime for projects that don't have any tasks, and the call to COALESCE() replaces the null with a 0 . 对于没有任何任务的项目,您在totalTime获得NULLS ,并且对COALESCE()的调用将null替换为0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM