[英]Get all entries from one table together with the count of these entries in another table
I've got 3 tables: 我有3张桌子:
How do I get all users together with the number of downloads they have? 如何获得所有用户以及他们的下载数量?
How do I get all users together with the number of downloads they have? 如何获得所有用户以及他们的下载数量?
Use: 采用:
SELECT u.name,
COUNT(d.user_id) 'num_downloaded'
FROM USERS u
OIN DOWNLOADS d ON d.user_id = u.user_id
GROUP BY u.name
If you want to see how many times a user has downloaded a specific item: 如果要查看用户下载特定项目的次数:
SELECT u.name 'user_name',
i.name 'item_name',
COUNT(d.user_id) 'num_downloaded'
FROM USERS u
JOIN DOWNLOADS d ON d.user_id = u.user_id
JOIN ITEMS i ON i.item_id = d.item_id
GROUP BY u.name, i.name
This should do it: 应该这样做:
SELECT u.name as name, count(*) as downloads
FROM users u, items i, downloads d
WHERE u.id = i.user_id AND i.user_id = d.user_id;
I had to invent items.user_id
, but it should be available. 我必须发明items.user_id
,但它应该可用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.