Is it possible to GROUP BY
more than one column in a MySQL SELECT
query? For example:
GROUP BY fV.tier_id AND 'f.form_temp开发者_如何学JAVAlate_id'
GROUP BY col1, col2, col3
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.
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
Meanwhile, the code
GROUP BY f.form_template_id, fV.tier_id
would give similar results, but sorted differently.
group by fV.tier_id, f.form_template_id
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.
SELECT pagename, COUNT(DISTINCT ipaddress) AS visit_count FROM log_visitors GROUP BY pagename ORDER BY visit_count DESC;
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
GROUP BY CONCAT(col1, '_', col2)
精彩评论