简体   繁体   English

如何在 MySQL 的一个查询中将多个“分组依据”输出作为列

[英]how to get multiple 'group by' outputs as columns in one query in MySQL

I have a table with 3 columns我有一个有 3 列的表

table data and structure:表数据和结构:

id|username|work_type|points

----------

1|user 1  |walking  |1500
2|user 1  |running  |1500
3|user 2  |walking  |2500
4|user 3  |running  |1500
5|user 4  |walking  |1500
6|user 4  |walking  |1200

I need this output:我需要这个 output:

username|walking|running|points
user 1  |      1|      1|3000
user 2  |      1|      0|2500
user 3  |      0|      1|1500
user 4  |      2|      0|2700

what I have done:我做了什么:

Select * FROM (
Select Count(id),username as "username" from table where work_type='walking' group by username)
 USERNAME LEFT JOIN
Select Count(id),username as "walking" from table where work_type='walking' group by username)
 WALKING ON USERNAME.username=WALKING.username LEFT JOIN
Select Count(id),username as "running" from table where work_type='running' group by username)
 RUNNING ON USERNAME.username=RUNNING.username LEFT JOIN
Select SUM(points),username as "point" from table group by username)
 POINTS ON USERNAME.username=POINTS.username)

the above query gives the correct output, but since it takes 4 rounds in the same table it takes more time.上面的查询给出了正确的 output,但由于在同一个表中需要 4 轮,因此需要更多时间。 this is only a logical structure of my actual DB table but it's similar.这只是我的实际数据库表的逻辑结构,但它是相似的。 where it takes 1.4-2.1 Seconds since there are over 50k rows in the lowest one.它需要 1.4-2.1 秒,因为在最低的行中有超过 50k 行。 I need to run the same query for 17 tables like this in one go.我需要在一个 go 中对 17 个这样的表运行相同的查询。 my time limit is about 20 seconds with about 2M+ rows.我的时间限制是大约 20 秒,大约 2M+ 行。 currently, it takes over 1 minute.目前,它需要超过 1 分钟。

I don't think my SQL query is efficient.我认为我的 SQL 查询效率不高。 is there some way I can speed this up?.有什么办法可以加快速度吗? this is a DB that has been running for 3 years+ for commercial uses, so I cannot change the structures.这是一个已运行 3 年以上用于商业用途的数据库,因此我无法更改结构。 these tables also need a left join from another table as well, but that I can build a different system for that if needed.这些表也需要来自另一个表的左连接,但如果需要,我可以为此构建一个不同的系统。

This kind of question is asked rather often.这种问题经常被问到。 Generally, I think it's best resolved in application code, but anyway...一般来说,我认为最好在应用程序代码中解决,但无论如何......

SELECT username
     , SUM(work_type = 'running') running
     , SUM(work_type = 'walking') walking
     , SUM(points) total 
  FROM my_table GROUP BY username;

The 'application code' version might look something like this: “应用程序代码”版本可能如下所示:

SELECT username
     , work_type
     , COUNT(*) cnt 
     , SUM(points) total 
  FROM my_table 
GROUP 
    BY username
     , work_type;

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

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