chris
chris

Reputation: 36937

MySQL multi sort / multi group query

Ok I am trying to construct a query that will give me results a-z and group them within there primary category. Each result should give me about 30 or more listings per category. However with this query.

select teamName, CONCAT(UCASE(leagueType)) as league
from fmr_teamNames 
group by leagueType 
order by teamName asc

I will only get a single listing per category. Which I understand to a point cause I am using a group by condition.

When I reorder the query a little and remove the group by condition I get all my listings but they are in z-a. When the desired goal is categories a-z then the inner results per category a-z

select teamName, CONCAT(UCASE(leagueType)) as league
from fmr_teamNames
order by leagueType asc

This currently gives me a-z on the categories, and z-a on the results per. So I am a little confused as to how to better form this query for my results, without having to use some outside intervention like PHP to reorder everything.

Upvotes: 0

Views: 223

Answers (1)

Fluffeh
Fluffeh

Reputation: 33512

I think you are mistaking the concat function for the group_concat function in mysql. Concat will append two strings together, while group_concat will merge rows together.

select teamName, group_concat(UCASE(leagueType)) as league
from fmr_teamNames 
group by teamName 
order by teamName asc

Your query also seemed to use a group by on the aggregated column rather than the unique one you are trying to identify?

Example:

mysql> select * from table1;
+---------+------+------+-------------+
| autonum | ID   | name | metavalue   |
+---------+------+------+-------------+
|       1 |    1 | Rose | Drinker     |
|       2 |    1 | Rose | Nice Person |
|       3 |    1 | Rose | Runner      |
|       4 |    2 | Gary | Player      |
|       5 |    2 | Gary | Funny       |
|       6 |    2 | Gary | NULL        |
|       7 |    2 | Gary | Smelly      |
+---------+------+------+-------------+
7 rows in set (0.00 sec)

mysql> select concat(autonum, ID) from table1 group by ID;
+---------------------+
| concat(autonum, ID) |
+---------------------+
| 11                  |
| 42                  |
+---------------------+
2 rows in set (0.00 sec)

mysql> select group_concat(autonum, ID) from table1 group by ID;
+---------------------------+
| group_concat(autonum, ID) |
+---------------------------+
| 11,21,31                  |
| 42,52,62,72               |
+---------------------------+
2 rows in set (0.01 sec)

Upvotes: 1

Related Questions