MySQL统计的两列分组

时间:2019-03-13 08:44:02

标签: mysql sql group-by

我有这张user_logs桌子:

user_id | operation | table
--------+-----------+-----------
1       | create    | restaurant
1       | create    | restaurant
1       | create    | dish type
1       | create    | dish type
1       | create    | dish type
1       | update    | dish name
1       | update    | dish name
1       | update    | dish name
1       | update    | restaurant
1       | update    | restaurant

我要填充该表的数据:

operation_on_table | count
-------------------+------
create restaurant  | 2
create dish type   | 3
update dish name   | 3
update restaurant  | 2

我到目前为止所做的是:

SELECT operation, count(operation) FROM user_logs
WHERE user_id = 1
GROUP BY operation

它给了我这个

operation | count
----------+------
create    | 5
update    | 5

但这不是我所需要的。

如何将表名添加到计数中?

4 个答案:

答案 0 :(得分:3)

在分组依据中添加table

SELECT operation,`table`, count(operation) 
FROM user_logs
WHERE user_id = 1
GROUP BY operation,`table`

答案 1 :(得分:2)

GROUP BY这两列,并在select内串联这些列:

SELECT CONCAT_WS(' ', `operation`, `table`) AS `operation_on_table`
     , COUNT(*) AS `count`
FROM `user_logs`
WHERE `user_id` = 1
GROUP BY `operation`, `table`

答案 2 :(得分:1)

简单的查询即可完成工作:

select operation, count(*) from (
   select concat(operation, ' ', `table`) `operation` from user_logs
) a group by operation

答案 3 :(得分:1)

  

您可以尝试

select operation,[table], count(operation) from  user_logs 
GROUP BY operation,[table]