如何在三张桌子上进行完全外连接?
我已经在两个表上成功地加入了我的连接,但是我对如何将第三个表添加到我的查询中一无所知。
这是我的(啰嗦)查询:
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)
非常感谢任何指导。
答案 0 :(得分:4)
尝试此查询 -
(适用编辑)强>
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