我想在下面加入的两个表格是表格的详细信息
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
问题
我想以一种方式加入users
和trophy_lookup
表,我可以计算用户赢得多少trophis以及用户名以下是我希望实现的所需输出。
user_id| name | count(trophis)
1 | john | 2
2 | jacky| 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
| 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
| 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 ;