我有两个表,主键和列(名称颜色)
Table1
|Color|
|red |
|green|
|blue |
Table2
|Color|
|red |
|red |
|green|
我试过
SELECT (
SELECT COUNT(*)
FROM table1
) AS count1,
(
SELECT COUNT(*)
FROM table2
) AS count2
但这给出了
count1|count2|
3 |3 |
如何获得与颜色类似的输出
|Color|count1| count2
|red | 1 |2
|green| 1 |1
|blue |1 |0
答案 0 :(得分:1)
SELECT
color
, MAX(CASE WHEN tabl = 'T1' THEN count_of END) count1
, MAX(CASE WHEN tabl = 'T2' THEN count_of END) count2
FROM (
SELECT 'T1' tabl, Color, COUNT(*) count_of FROM table1 GROUP BY Color
UNION ALL
SELECT 'T2' tabl , Color , COUNT(*) FROM table2 GROUP BY color
) d
GROUP BY color
答案 1 :(得分:1)
您好sri只是您可以使用union和group by
select id,color, sum(coun_t) as counts from (
(SELECT id,color,count(*) as coun_t FROM `table1` group by color)
union
(SELECT id,color,count(*) as coun_t FROM `table2` group by color)
) as p group by color order by id asc