[英]mysql: query combining info from 2 tables
Suppose the following configuration: 假设以下配置:
When there is info to be stored, there will be records added to the info table. 当存储信息时,将在信息表中添加记录。 I can easily get a nice overview of the number of records for each user like: 我可以很容易地得到每个用户的记录数量的一个很好的概述,如:
mysql> SELECT userId ,COUNT(*) as nbr_entries FROM info GROUP BY userId ORDER BY nbr_entries DESC;
+-----------+-------------+
| userId | nbr_entries |
+-----------+-------------+
| 3987 | 2254 |
| 11220 | 1922 |
...
Now, my question: I would like to have each userId to be looked up in Table 1 (generic), so that my query result would like like: 现在,我的问题:我希望在表1(通用)中查找每个userId,以便我的查询结果如下:
+-----------+-----------+-------------+
| name | userId | nbr_entries |
+-----------+-----------+-------------+
| Peter | 3987 | 2254 |
| Walter | 11220 | 1922 |
...
Any idea how to achieve this? 知道怎么做到这一点? Thanks in advance. 提前致谢。
You could use JOIN
你可以使用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;
You can use subquery
& JOIN
您可以使用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;
Use a LEFT JOIN: 使用LEFT JOIN:
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
This way you will also include users who has no info entries (yet) and get 0
as nbr_entries
. 这样,您还将包括没有信息条目的用户(还),并将0
作为nbr_entries
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.