的一種方式,使用GROUP_CONCAT將可能的值分組爲字符串,然後使用SUBSTRING_INDEX獲取每個值(如果存在)。
SELECT x.id,
x.uniqueid,
x.name,
IF(COUNT(y.id) >= 1, SUBSTRING_INDEX(GROUP_CONCAT(y.code ORDER BY y.code), ',', 1), NULL) AS code1,
IF(COUNT(y.id) >= 1, SUBSTRING_INDEX(GROUP_CONCAT(y.value ORDER BY y.code), ',', 1), NULL) AS value1,
IF(COUNT(y.id) >= 2, SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(y.code ORDER BY y.code), ',', 2), ',', -1), NULL) AS code2,
IF(COUNT(y.id) >= 2, SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(y.value ORDER BY y.code), ',', 2), ',', -1), NULL) AS value2,
IF(COUNT(y.id) >= 3, SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(y.code ORDER BY y.code), ',', 3), ',', -1), NULL) AS code3,
IF(COUNT(y.id) >= 3, SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(y.value ORDER BY y.code), ',', 3), ',', -1), NULL) AS value3,
IF(COUNT(y.id) >= 4, SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(y.code ORDER BY y.code), ',', 4), ',', -1), NULL) AS code4,
IF(COUNT(y.id) >= 4, SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(y.value ORDER BY y.code), ',', 4), ',', -1), NULL) AS value4,
IF(COUNT(y.id) >= 5, SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(y.code ORDER BY y.code), ',', 5), ',', -1), NULL) AS code5,
IF(COUNT(y.id) >= 5, SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(y.value ORDER BY y.code), ',', 5), ',', -1), NULL) AS value5
FROM tbl_user x
LEFT JOIN tbl_transaction y
ON y.userid = x.id
GROUP BY x.id,
x.uniqueid,
x.name
但你需要的代碼來應付值
什麼是錯誤的查詢列的最大數量? –
沒有錯誤,但有結果 –
我不知道你是否可以做到這一點,但你可以使用'GROUP_CONCAT'在這裏看到文檔:http://dev.mysql.com/doc/refman/5.7/en/group -by-functions.html#function_group-concat –