Full Outer Join on Three Tables

久未见 提交于 2020-01-05 07:52:17

问题


How would one carry out a full outer join on three tables?

I have already carried my join successfully on two tables, but I am clueless on how to add the third table to my query.

Here is my (long-winded) query:

SELECT MONTH(t1.datetime) AS month, COUNT(DISTINCT t1.column) AS t1Count, COUNT(DISTINCT t2.column) AS t2Count
FROM t1
LEFT OUTER JOIN t2 ON MONTH(t2.datetime) = MONTH(t1.datetime)
GROUP BY MONTH(t1.datetime)
UNION
SELECT MONTH(t1.datetime) AS month, COUNT(DISTINCT t1.column) AS t1Count, COUNT(DISTINCT t2.column) AS t2Count
FROM t1 
RIGHT OUTER JOIN t2 ON MONTH(t2.datetime) = MONTH(t1.datetime)
GROUP BY MONTH(t2.datetime)

Any guidance is much appreciated.


回答1:


Try this query -

(edited)

SELECT
  t.month,
  COUNT(DISTINCT t1.column) t1count,
  COUNT(DISTINCT t2.column) t2count,
  COUNT(DISTINCT t3.column) t3count
FROM 
  (SELECT MONTH(datetime) AS month FROM t1
    UNION
  SELECT MONTH(datetime) AS month FROM t2
    UNION
  SELECT MONTH(datetime) AS month FROM t3
  ) t
  LEFT JOIN t1
    ON t.month = MONTH(t1.datetime)
  LEFT JOIN t2
    ON t.month = MONTH(t2.datetime)
  LEFT JOIN t3
    ON t.month = MONTH(t3.datetime)
  GROUP BY
    month


来源:https://stackoverflow.com/questions/9226127/full-outer-join-on-three-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!