php - MySQL多排序/多组查询

标签 php mysql

好吧,我正在尝试构建一个查询,该查询将为我提供结果 a-z 并将它们分组到主要类别中。每个结果应该为我提供每个类别大约 30 个或更多的列表。但是通过这个查询。

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

每个类别我只会获得一个列表。我在一定程度上理解这一点,因为我正在使用按条件分组。

当我稍微重新排序查询并删除按条件分组时,我得到了所有列表,但它们位于 z-a 中。当所需目标是类别 a-z 时,则每个类别 a-z 的内部结果

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

目前,这为我提供了类别的 a-z 以及每个结果的 z-a。因此,我对如何更好地为我的结果形成此查询感到有点困惑,而不必使用 PHP 等外部干预来重新排序所有内容。

最佳答案

我认为您将concat函数误认为是mysql中的group_concat函数。 Concat 会将两个字符串附加在一起,而 group_concat 会将行合并在一起。

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

您的查询似乎还在聚合列上使用了group by,而不是您尝试识别的唯一列?

示例:

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)

关于php - MySQL多排序/多组查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12333054/

相关文章:

mysql - 使用 SQL 根据单条记录的更改来更改多条记录

javascript - MVC架构如何应用于Web应用程序开发?

php - 如何在 Url 中隐藏 .php 扩展名

php - PayPal 自适应支付错误 540031

php - 如何在日期变量中连接特定月份?

php - 如何根据 codeigniter 中的特定值显示行数

php - IMAP 通过 PHP :/ssl and/tls choose different TLS version

php - Android + 网站/服务器上的 Facebook 身份验证

mysql - 带聚合函数的子查询

php - 在 mySQL 中扩展餐厅数据库