是否可以使用 MySQL 对多个列进行 GROUP BY?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1841426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to GROUP BY multiple columns using MySQL?
提问by Rhys Thought
Is it possible to GROUP BY
more than one column in a MySQL SELECT
query? For example:
GROUP BY
MySQLSELECT
查询中是否可以有多个列?例如:
GROUP BY fV.tier_id AND 'f.form_template_id'
回答by Joe Phillips
GROUP BY col1, col2, col3
回答by php
Yes, you can group by multiple columns. For example,
是的,您可以按多列分组。例如,
SELECT * FROM table
GROUP BY col1, col2
The results will first be grouped by col1, then by col2. In MySQL, column preference goes from left to right.
结果将首先按 col1 分组,然后按 col2。在 MySQL 中,列首选项从左到右。
回答by brandonCabi
Yes, but what does grouping by more two columns mean? Well, it's the same as grouping by each unique pair per row. The order you list the columns changes the way the rows are sorted.
是的,但是按更多两列分组是什么意思?嗯,这与按每行的每个唯一对进行分组相同。您列出列的顺序会改变行的排序方式。
In your example, you would write
在你的例子中,你会写
GROUP BY fV.tier_id, f.form_template_id
GROUP BY fV.tier_id, f.form_template_id
Meanwhile, the code
同时,代码
GROUP BY f.form_template_id, fV.tier_id
GROUP BY f.form_template_id, fV.tier_id
would give similar results, but sorted differently.
会给出类似的结果,但排序不同。
回答by Trevor
group by fV.tier_id, f.form_template_id
回答by Daniklad
To use a simple example, I had a counter that needed to summarise unique IP addresses per visited page on a site. Which is basically grouping by pagename and then by IP. I solved it with a combination of DISTINCT and GROUP BY.
举一个简单的例子,我有一个计数器,需要汇总站点上每个访问页面的唯一 IP 地址。这基本上是按页面名称分组,然后按 IP 分组。我用 DISTINCT 和 GROUP BY 的组合解决了它。
SELECT pagename, COUNT(DISTINCT ipaddress) AS visit_count FROM log_visitors GROUP BY pagename ORDER BY visit_count DESC;
回答by Lucas Andrade
If you prefer (I need to apply this) group by two columns at same time, I just saw this point:
如果你更喜欢(我需要应用这个)同时按两列分组,我刚刚看到了这一点:
SELECT CONCAT (col1, '_', col2) AS Group1 ... GROUP BY Group1
回答by lada
GROUP BY CONCAT(col1, '_', col2)