晚上好
我在尝试找到连接两个表的解决方案时遇到问题:
比如我有
表 1:
Date | Item
12/03 | aaaa
12/03 | aaaa
14/03 | bbbb
14/03 | aaaa
15/03 | cccc
表 2:
Date | Item2
11/03 | aaaa
12/03 | aaaa
13/03 | bbbb
14/03 | aaaa
15/03 | cccc
我想做一个计数来得到这个
Date | Count(Item1) | Count(Item2)
11/03 | 0 | 1
12/03 | 2 | 1
13/03 | 0 | 1
14/03 | 2 | 1
15/03 | 1 | 1
到目前为止我已经试过了,但它似乎没有用,它只给我公共(public)日期:
SELECT F.DATE, COUNT(T1.Item1), COUNT(T2.Item2) FROM TABLE1
T1 LEFT JOIN TABLE2 T2 ON T1.date=T2.date
Date | Count(Item1) | Count(Item2)
12/03 | 2 | 1
14/03 | 2 | 1
15/03 | 1 | 1
有什么帮助吗?
谢谢
最佳答案
In the below SQL, the first inline view is computing all the counts at date level and same applies with second query. By combining the results of left join and right join between these two inline views we can combine all the common and uncommon results from both tables as you described.
SELECT Date,
Item1,
Item2
FROM
(
SELECT T1.Date AS Date,
COUNT( T1.Item ) AS Item1,
COUNT( T2.Item ) AS Item2
FROM Table1 t1
LEFT JOIN
Table2 t2
ON t1.date = t2.date
GROUP BY t1.Date
UNION
SELECT T2.Date AS Date,
COUNT( T1.Item ) AS Item1,
COUNT( T2.Item ) AS Item2
FROM Table2 t2
LEFT JOIN
Table1 t1
ON t2.date = t1.date
GROUP BY t2.Date
) A
ORDER BY Date
;
SQL Fiddle 实现:-
关于mysql - 使用 SQL 将两个表连接到一个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39732983/