简体   繁体   English

从一个表中获取所有条目以及在另一个表中的这些条目的计数

[英]Get all entries from one table together with the count of these entries in another table

I've got 3 tables: 我有3张桌子:

  • users (id, name, ...) 用户(ID,名称等)
  • items (id, name, ...) 项目(ID,名称,...)
  • downloads (user_id, item_id, ...) 下载(user_id,item_id等)

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.

相关问题 PostgreSQL根据给定的id和mutiple计算来自一个表的条目,并根据另一表的比率对其求和 - PostgreSQL count entries from one table for a given id and mutliple that by rates in another table and sum it all up 对于一个表中的所有条目,添加到另一个表中 - For all entries in one table, add to another table 从一个表中选择所有条目,在另一个表中有两个特定条目 - Select all entries from one table which has two specific entries in another table SQL筛选器条目与另一个表中的所有条目匹配 - SQL filter entries which match all entries from another table 根据另一个表中的计数条目更新一个表中的列值 - Update Column Value in one table based on count entries in another table SQL Server在一个表中对另一个表计数条目 - SQL Server count entries in one table against another table 如果 RIGHT 表中没有条目,则获取计数 0 - Get Count 0 if there are no entries in the RIGHT Table 从一个表中获取变量的情况计数,以使其在SQLlite中不同表的另一列中的条目不同? - Getting count of cases of a variable from one table such that its entries are different in an another column of different table in SQLlite? 循环执行SQL以获取与另一个表关联的表中的所有条目 - Looping in SQL to get all entries in a table associated with another table 获取一个表的所有行,并从另一个表中匹配行,其中SQL中可能不存在条目 - Getting all rows of one table, and matching rows from another table where entries may not exist in SQL
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM