计数记录和连接表

时间:2013-05-17 09:21:56

标签: php mysql sql jointable

我想在下面加入的两个表格是表格的详细信息

Trophy_lookup表包含

id | user_id | trophy_id
1  | 2       | 2
2  | 3       | 4
3  | 1       | 5
4  | 2       | 1
4  | 1       | 1

Users表包含一般用户信息

id | name    | email
1  | john    | john@webcom
2  | jacky   | jacky@web.com
3  | Smith   | smith@web.com
4  | Rob     | rob@web.com

问题 我想以一种方式加入userstrophy_lookup表,我可以计算用户赢得多少trophis以及用户名以下是我希望实现的所需输出。

user_id| name | count(trophis)
     1 | john | 2
     2 | jacky| 2

到目前为止,我已经尝试了很多东西但是我无法达到上述效果。我对编写查询不太满意,所以请指导我。感谢

2 个答案:

答案 0 :(得分:2)

尝试此查询

select a.id, a.name, count(*) as cnt
from table2 a 
inner join 
table1 b
on a.id = b.user_id
group by 
a.id, a.name
having count(*) > 1
order by cnt

SQL FIDDLE

| ID |  NAME | CNT |
--------------------
|  2 | jacky |   2 |
|  1 |  john |   2 |

替代方法

select a.name, b.* 
from table2 a
inner join 
(select a.id, count(*) as cnt
from table2 a 
inner join 
table1 b
on a.id = b.user_id
group by 
a.id) b 
ON a.id=b.id
where cnt > 1

SQL FIDDLE

|  NAME | ID | CNT |
--------------------
|  john |  1 |   2 |
| jacky |  2 |   2 |

答案 1 :(得分:0)

尝试此查询:

SELECT u.id,count(u.id),u.name 
FROM trophy_lookup t 
JOIN users u ON t.user_id=u.id 
GROUP BY u.id ;