我有一個 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_TEACHER | 電話 | NUMBER |
---|---|---|
#1 | 1 | xxxxxxx |
1 | 2 | xxxxxxxx |
1 | 3 | xxxxxxx |
2 | 1 | xxxxxxx |
但是,我希望它顯示如下:
ID_TEACHER | 電話 | NUMBER | #電話 | NUMBER | #電話 | NUMBER |
---|---|---|---|---|---|---|
#1 | 1 | xxxxx | 2 | xxxxx | 3 | xxxxx |
2 | 1 | xxxxxxxxx |
我該怎麼辦?我正在使用MYSQL。我沒有找到解決方案。
P粉4760461652023-09-10 00:56:25
您需要使用條件聚合:
嘗試以下操作:
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