MySQL未知列数的行转列查询方法(mysql不确定的行转列)
MySQL:未知列数的行转列查询方法
在MySQL中,通常我们可以使用PIVOT函数来实现将行转列的操作。然而,当我们不知道列的数量时,如何进行行转列的查询呢?接下来,我们将介绍一种未知列数的行转列查询方法。
假设我们有以下一张学生表(table_students):
| id | name | subject | score |
|—-|——-|———-|——-|
| 1 | Alice | English | 85 |
| 2 | Alice | Math | 75 |
| 3 | Alice | Science | 90 |
| 4 | Bob | English | 80 |
| 5 | Bob | Math | 70 |
| 6 | Bob | Science | 95 |
我们想要将学生表转换为以下的形式:
| name | English | Math | Science |
|——-|———|——|———|
| Alice | 85 | 75 | 90 |
| Bob | 80 | 70 | 95 |
步骤1:动态生成列名
我们需要生成一个包含所有可能出现的subject的列表,这样我们才能动态生成列名:
SELECT GROUP_CONCAT(DISTINCT
CONCAT(‘MAX(CASE WHEN subject = “‘,subject,'” THEN score END) AS “‘,subject,'”‘)
)
INTO @sql
FROM table_students;
该查询语句中使用了GROUP_CONCAT函数,用于将查询到的所有subject拼接成一个字符串,拼接之后的字符串形式为:
MAX(CASE WHEN subject = “English” THEN score END) AS “English”,
MAX(CASE WHEN subject = “Math” THEN score END) AS “Math”,
MAX(CASE WHEN subject = “Science” THEN score END) AS “Science”
步骤2:生成动态查询语句
接着,我们需要使用动态生成的列名来构建一条动态的查询语句:
SET @query = CONCAT(‘SELECT name, ‘,@sql,’ FROM table_students GROUP BY name’);
生成的查询语句为:
SELECT name,
MAX(CASE WHEN subject = “English” THEN score END) AS “English”,
MAX(CASE WHEN subject = “Math” THEN score END) AS “Math”,
MAX(CASE WHEN subject = “Science” THEN score END) AS “Science”
FROM table_students
GROUP BY name
步骤3:执行动态查询语句
使用PREPARE和EXECUTE语句来执行动态查询语句:
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
完整的查询语句如下所示:
SET @sql = NULL;
SET @query = NULL;
SELECT GROUP_CONCAT(DISTINCT
CONCAT(‘MAX(CASE WHEN subject = “‘,subject,'” THEN score END) AS “‘,subject,'”‘)
)
INTO @sql
FROM table_students;
SET @query = CONCAT(‘SELECT name, ‘,@sql,’ FROM table_students GROUP BY name’);
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
通过这样的方法,我们可以将行转列的操作变得非常灵活,适用于列数不确定的场景。