2013-04-12 63 views
-1

我有以下表任何人都可以教我嗎?mysql的連接表

 
table 1        table 2 
id q_id content     id | w_id | q_id | c_id | ranking 
----------------------   ------------------------------------------------ 
95 2046 1=E      123 | 22404 | 2046 | 100 | 1 

96 2046 2=G      124 | 22404 | 2046 | 101 | 2 

97 2046 3=N      125 | 22404 | 2046 | 102 | 2 

98 2046 4=B      126 | 22404 | 2046 | 103 | 2 

99 2046 5=V      127 | 22404 | 2046 | 104 | 3 

100 2046 A1      128 | 22404 | 2046 | 105 | 3 

101 2046 A2      129 | 22405 | 2046 | 100 | 4 

102 2046 A3      130 | 22405 | 2046 | 101 | 4 

103 2046 A4      131 | 22405 | 2046 | 102 | 1 

104 2046 A5      132 | 22405 | 2046 | 103 | 2 

105 2046 A6      133 | 22405 | 2046 | 104 | 2 

            134 | 22405 | 2046 | 105 | 3 

我需要寫一個SQL,這樣我可以得到以下結果

w_id | q_id | A1 | A2 | A3 | A4 | A5 | A6 
--------------------------------------------------- 
22404 | 2046 | 1 | 2 | 2 | 2 | 3 | 3 
22405 | 2046 | 4 | 4 | 1 | 2 | 2 | 3 

誰能幫助我

+0

如果你能有列任意數量的,不只是100-105,那麼你需要一個支點。否則,只能通過連接完成。 – Patashu

+0

我使用mySQL,不能使用數據透視你能告訴我另一種方法嗎? – user2210819

+0

Google'mySQL pivot' – Patashu

回答

1

沒有必要加入這些表格。

你可能需要的東西是這樣的:

SELECT w_id as W , q_id, 
(select ranking from table2 where w_id = W and c_id = 100) as 100, 
(select ranking from table2 where w_id = W and c_id = 101) as 101, 
(select ranking from table2 where w_id = W and c_id = 102) as 102, 
(select ranking from table2 where w_id = W and c_id = 103) as 103, 
(select ranking from table2 where w_id = W and c_id = 104) as 104, 
(select ranking from table2 where w_id = W and c_id = 105) as 105 
FROM table2; 
+0

非常感謝, 我想我需要修改如上圖所示 你能不能給我看動態的? – user2210819

相關問題