简体   繁体   English

在一个查询中计算MySQL中的多行

[英]Counting multiple rows in MySQL in one query

I currently have a table which stores a load of statistics such as views, downloads, purchases etc. for a multiple number of items. 我目前有一个表,可以存储大量项目的统计信息,例如视图,下载,购买等。 To get a single operation count on each item I can use the following query: 为了获得每个项目的单个操作计数,我可以使用以下查询:

SELECT *, COUNT(*)
FROM stats
WHERE operation = 'view'
GROUP BY item_id

This gives me all the items and a count of their views. 这给了我所有的项目和他们的观点。 I can then change 'view' to 'purchase' or 'download' for the other variables. 然后,我可以将“查看”更改为“购买”或“下载”其他变量。 However this means three separate calls to the database. 但是,这意味着对数据库进行三次单独调用。

Is it possible to get all three in one go? 是否有可能将三者合二为一?

SELECT item_id, operation, COUNT(*) 
FROM stats 
WHERE operation IN ('view','purchase','download') 
GROUP BY item_id, operation

Will return a table with one line per item_id and operation , containing three columns: the item_id, the operation type, and the number of rows with that item_id. 将返回一个表, 每个item_id和操作包含一行 ,包含三列:item_id,操作类型和具有该item_id的行数。

1 view 3
1 purchase 5
2 download 7
3 download 1

You can omit the WHERE if you want all item_id's, and you can order in COUNT(*) to get the most popular or something. 如果你想要所有item_id,你可以省略WHERE,你可以在COUNT(*)中订购以获得最受欢迎的东西。 Depends what you are looking for or how you are using the data. 取决于您要查找的内容或您使用数据的方式。

If you want the columns next to eachother , use an IF: 如果您希望彼此旁边的列,请使用IF:

SELECT s1.item_id, SUM( IF( s1.operation = 'view', 1, 0 ) ) views, SUM( IF( s1.operation = 'download', 1, 0 ) ) downloads, SUM( IF( s1.operation = 'purchase', 1, 0 ) ) purchases
FROM stats s1
GROUP BY s1.item_id

item_id | views | downloads | purchases
1 | 3 | 0 | 5
2 | 0 | 7 | 0
3 | 0 | 1 | 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM