SQLite3 Simulate RIGHT OUTER JOIN with LEFT JOINs and UNION

后端 未结 1 677
抹茶落季
抹茶落季 2021-02-20 14:20

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:

相关标签:
1条回答
  • 2021-02-20 14:54

    Even though SQLite hasn't implemented RIGHT OUTER or FULL OUTER, it does have LEFT OUTER JOIN, which should do what you'd like. Just have tbProjects be on the left.

    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.

    0 讨论(0)
提交回复
热议问题