如何在一行中统一记录- MYSQL

aydmsdu9  于 2023-03-28  发布在  Mysql
关注(0)|答案(1)|浏览(127)

我有一个teacher表,我还有一个phone表,其中的链接是通过人的ID。当我查找每个教授的电话号码时,它看起来像这样:

(SELECT
       T.ID_TEACHER,
       P.PHONE,
       P.NUMBER 
FROM TEACHER T LEFT JOIN PHONES P 
ON P.IDPERSON = T.ID_TEACHER)
ID_教师联系电话编号
11xxxxxxx
1xxxxxxxx
1xxxxxxx
1xxxxxxx

但是,我希望它是这样显示的:
| ID_教师|联系电话|编号|联系电话|编号|联系电话|编号|
| --------------|--------------|--------------|--------------|--------------|--------------|--------------|
| 1|1|xxxxx|二|xxxxx|三|xxxxx|
| 二|1|啊|||||
我怎么办?我用的是MySQL。我没找到解决办法。

8i9zcol2

8i9zcol21#

您需要使用条件聚合:
请尝试以下操作:

SELECT
    T.ID_TEACHER,
    MAX(CASE WHEN P.PHONE = 1 THEN P.PHONE ELSE NULL END) AS PHONE1,
    MAX(CASE WHEN P.PHONE = 1 THEN P.NUMBER ELSE NULL END) AS NUMBER1,
    MAX(CASE WHEN P.PHONE = 2 THEN P.PHONE ELSE NULL END) AS PHONE2,
    MAX(CASE WHEN P.PHONE = 2 THEN P.NUMBER ELSE NULL END) AS NUMBER2,
    MAX(CASE WHEN P.PHONE = 3 THEN P.PHONE ELSE NULL END) AS PHONE3,
    MAX(CASE WHEN P.PHONE = 3 THEN P.NUMBER ELSE NULL END) AS NUMBER3
FROM TEACHER T
LEFT JOIN PHONES P ON P.IDPERSON = T.ID_TEACHER
GROUP BY T.ID_TEACHER

相关问题