2017-01-06 87 views
0

我有2個表,各個列和tokenid對於兩者都是相同的。 第二個表有多個具有相同tokenid的行,其他列是不同的。從2個表中選擇列作爲具有相同ID的列作爲列

現在,我需要從這兩個表中的列表中選擇標記id相同的列,並且在第二個表中,具有相同tokenid的行必須轉換爲列。

表1:

tokenid acolumn1 acolumn2 acolumn4 
    1  fname1  mname1  lname1 
    2  fname2  mname2  lname2 

表2:

id tokenid bquestion banswer 
1  1  questiona answera 
2  1  questionb answerb 
3  2  questiona answera 
4  2  questionb answerb 
5  3  questionc answerc 

結果應該是

tokenid acolumn1 acolumn2 acolumn3 bquestion1 banswer1 bquestion2 banswer2 bquestion3 banswer3 
    1  fname1  mname1  lname1  questiona answera questionb answerb null   null 
    2  fname2  mname2  lname2  questiona answera questionb answerb questionc answerc 

我試圖首先用不同查詢第二表,並用它作爲一個子查詢加入table1。但數據庫在表2中有超過200,000行,並且與由acolumn1選擇的tokenid匹配將產生約20000行結果。所以我的查詢沒有完成。有沒有優化的方法來解決這個問題?

P.S:我想補充一點,我使用PDO

+2

的可能的複製[MySQL的數據透視表(http://stackoverflow.com/questions/7674786/mysql-pivot-table) – shmosel

+0

還有,你試過這麼遠嗎? –

+0

@ shA.t就像我說過的,嘗試使用LEFT JOIN,使用像select colums(從...中選擇列)這樣的子查詢。問題是,我有巨大的數據庫和大多數查詢未能成功加載 – Vijai

回答

-2

試試這個代碼這個加入您的Table 1和表2中的所有列做用PHP查詢。

Click here to see output

SELECT table1.tokenid, table1.acol1, table1.acol2, table1.acol3, table2.bquestion, table2.banswer FROM table1 
    INNER JOIN table2 
    ON table1.tokenid=table2.tokenid 
相關問題