gpt4 book ai didi

mysql - 从单个表中仅在一行中添加多行

转载 作者:行者123 更新时间:2023-12-01 12:52:20 27 4
gpt4 key购买 nike

如何通过 mysql 将多行连接成一行?

示例:

学生表

Sno.| Name  |  Subjects
1. | ABC | English
2. | ABC | Mathematics
3. | ABC | Science
4. | FMC | French
5. | ABC | Russian
6. | JBC | French

现在我想要这种格式

Sno.| Name |   Sub1 |  Sub2 | Sub3 |  Sub4 |
1. | ABC | Eng | Maths| Science| Russian
2. | FMC | French| Null| Null | Null
3. | JBC | French| Null | Null | Null

我不知道该怎么做?我应该创建一个 View 还是一个表?

我想一个 View 就可以了。

最佳答案

我同意其他答案,GROUP_CONCAT 与 PHP 一起拆分逗号分隔值可能是最好的方法,但是如果出于任何其他原因您需要通过 Pure SQL I 建议的输出会建议以下方法之一。

1. Self Joins

SELECT  t1.Name, 
MIN(t1.Subject) AS Sub1,
MIN(t2.Subject) AS Sub2,
MIN(t3.Subject) AS Sub3,
MIN(t4.Subject) AS Sub4
FROM Students t1
LEFT JOIN Students T2
ON t1.Name = t2.Name
AND t2.Subject > t1.Subject
LEFT JOIN Students T3
ON t2.Name = t3.Name
AND t3.Subject > t2.Subject
LEFT JOIN Students T4
ON t3.Name = t4.Name
AND t4.Subject > t3.Subject
GROUP BY t1.Name;

2. Using a ROW_NUMBER Type function to aggregate

SELECT   Name,
MAX(IF(RowNum = 1,Subject, NULL)) AS Sub1,
MAX(IF(RowNum = 2,Subject, NULL)) AS Sub2,
MAX(IF(RowNum = 3,Subject, NULL)) AS Sub3,
MAX(IF(RowNum = 4,Subject, NULL)) AS Sub4
FROM ( SELECT Name,
Subject,
@r:= IF(@Name = Name, @r + 1, 1) AS RowNum,
@Name:= Name AS Name2
FROM Students,
(SELECT @Name:='') n,
(SELECT @r:= 0) r
ORDER BY Name, Sno
) t
GROUP BY Name

关于mysql - 从单个表中仅在一行中添加多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11509407/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com