2016-01-22 80 views
1

我有表,MySQL查詢連接兩個表並獲得結合兩排是一個

tbl_user

id uniqid name 
1 123456 AAAA 
2 333333 BBBB 

tbl_transaction

id userid code value 
1 1  2202 500000 
2 1  2204 700000 

和如何得到的結果即將被這樣

id uniqueid name code1 value1 code2 value2 
1 123456 AAAA 2202 500000 2204 700000 

我的查詢我只知道用加入這個我的代碼

SELECT x.id, x.uniqueid, x.name, y.value 
     FROM tbl_user x 
     LEFT JOIN tbl_transaction y 
      ON y.userid = x.id 
+0

什麼是錯誤的查詢列的最大數量? –

+0

沒有錯誤,但有結果 –

+0

我不知道你是否可以做到這一點,但你可以使用'GROUP_CONCAT'在這裏看到文檔:http://dev.mysql.com/doc/refman/5.7/en/group -by-functions.html#function_group-concat –

回答

0

我真的不知道它是否適用於ü只是試試看,

SELECT a.id,a.uniqueid,a.name,b.code,b.value,c.code,c.value FROM test.tbl_user as a,test.tbl_transaction as b,test.tbl_transaction as c where a.id=b.userid AND b.code!=c.code limit 1; 
+0

謝謝:)我會嘗試 –

1

的一種方式,使用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 

但你需要的代碼來應付值