假设以下配置:
当要存储信息时,会将记录添加到信息表中。我可以轻松地大致了解每个用户的记录数,例如:
mysql> SELECT userId ,COUNT(*) as nbr_entries FROM info GROUP BY userId ORDER BY nbr_entries DESC;
+-----------+-------------+
| userId | nbr_entries |
+-----------+-------------+
| 3987 | 2254 |
| 11220 | 1922 |
...
现在,我的问题是:我希望在表1(通用)中查找每个userId,以便我的查询结果如下:
+-----------+-----------+-------------+
| name | userId | nbr_entries |
+-----------+-----------+-------------+
| Peter | 3987 | 2254 |
| Walter | 11220 | 1922 |
...
任何想法如何实现这一目标? 预先感谢。
答案 0 :(得分:1)
您可以使用JOIN
SELECT b.name,userid,COUNT(*) as nbr_entries FROM info a
inner join generic b on a.userid=b.id
GROUP BY b.name,userId
ORDER BY nbr_entries DESC;
答案 1 :(得分:1)
您可以使用subquery
和JOIN
SELECT t1.name, t2.userId , t2.nbr_entries
FROM generic t1
JOIN
(SELECT userId ,COUNT(*) as nbr_entries FROM info GROUP BY userId) t2
ON t1.userId = t2.userId ORDER BY t2.nbr_entries DESC;
答案 2 :(得分:1)
使用左联接:
SELECT g.name, g.id as userId, COUNT(i.userId) as nbr_entries
FROM generic g
LEFT JOIN info i ON i.userId = g.id
GROUP BY g.id
ORDER BY nbr_entries DESC
这样,您还将包括还没有信息条目的用户,并将0
设为nbr_entries
。