任何人都可以教我连接表的SQL

时间:2013-04-12 08:40:42

标签: mysql sql join

我有以下表格:

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  

任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分: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;