MYSQL从不同的表中添加行和计数

时间:2012-03-29 10:09:22

标签: mysql database

我有两个表的mysql数据库。

第一(资料)

+---------+------+----------+
| species | sex  | user     |
+---------+------+----------+
| bird    | NULL |        1 |
| bird    | f    |        1 |
| cat     | f    |        1 |
| cat     | m    |        1 |
| dog     | f    |        1 |
| dog     | m    |        2 |
| hamster | f    |        2 |
| snake   | m    |        1 |
+---------+------+----------+

第二(用户)

+--------+-----+
| user   |  id |
+--------+-----+
| amy    | 1   |    
| dav    | 2   |  
| mot    | 3   |       
| mmm    | 4   | 
| aaw    | 5   | 
| dsa    | 6   |  
+--------+-----+

我想计算并显示表“users”中每个用户行的表“information”的值 喜欢这个

+---------+------+----------+
| user   |  id |  count     |
+---------+------+----------+
| amy    | 1    |        6  |
| dav    | 2    |        2  |
| mot    | 3    |        0  |
| mmm    | 4    |        0  |
| aaw    | 5    |        0  |
| dsa    | 6    |        0  |
+---------+------+----------+

我该如何进行此查询?

2 个答案:

答案 0 :(得分:1)

select users.user, users.id, count (species.name)
from users left join species 
on users.id = species.user
group by users.user, users.id
order by count (species.name) desc

答案 1 :(得分:0)

不是这样的:

select u.user, u.id, count(i.user)  
from user u  
  inner join information i on i.user = u.id  
group by u.user, u.id