MYSQL计数和连接查询

时间:2017-04-24 12:08:41

标签: php mysql

表:用户

Color
1
2
2
2
1
3

表:颜色

ID      Name
1       Orange
2       Yellow
3       Pink
4       Blue

预期结果

Color      Total
Orange     2
Yellow     3
Pink       1

Mysql查询:

SELECT * FROM User LEFT JOIN Color ON Color.ID = User.Color;

如何获得预期结果?请帮我。并提前感谢。

3 个答案:

答案 0 :(得分:0)

SELECT c.NAME, COUNT(*) AS Total 
FROM Color c
INNER JOIN User u ON (u.Color = c.Id)
GROUP BY c.NAME;

答案 1 :(得分:0)

这将有助于您这样做。兄弟:)

SELECT C.Name, COUNT(U.Color) as Total from Color C
            LEFT JOIN User U 
            ON
            U.Color = C.ID
            GROUP by C.ID,C.Name

谢谢!

答案 2 :(得分:0)

@Shah Rushabh使用U.Color的小组,如下所示,你会得到你的结果:

SELECT C.Name, COUNT(U.Color) as Total from user as U 
inner join color as C on 
U.Color = C.Id GROUP BY U.Color