2014-12-07 112 views
0

我有兩個表 - 字符串的表1和表2的字符串。用第二個查找表解碼一個表的SQL查詢

Table 1: 
+-------+-------+-------+-------+-------+ 
|  | col A | col B | col C | col D | 
+-------+-------+-------+-------+-------+ 
| row 1 |  1 |  |  |  | 
| row 2 |  |  2 |  |  | 
| row 3 |  8 |  3 |  |  | 
| row 4 |  9 |  |  4 |  | 
+-------+-------+-------+-------+-------+ 

Table 2: 
+-------+-------+--------------+ 
|  | col A | col B  | 
+-------+-------+--------------+ 
| row 1 |  1 | dog   | 
| row 2 |  2 | cat   | 
| row 3 |  3 | zebra  | 
| row 4 |  4 | donkey  | 
| row 5 |  8 | horse  | 
| row 6 |  9 | honey badger | 
+-------+-------+--------------+ 

是否有SQL查詢將返回以下內容?

+-------+--------------+-------+--------+-------+ 
|  | col A  | col B | col C | col D | 
+-------+--------------+-------+--------+-------+ 
| row 1 | dog   |  |  |  | 
| row 2 |    | cat |  |  | 
| row 3 | horse  | zebra |  |  | 
| row 4 | honey badger |  | donkey | horse | 
+-------+--------------+-------+--------+-------+ 

此刻我是SELECT * IN Table_1。 然後查詢Table_2六次以獲得結果。有更加優雅的方式嗎?

我想要使用SELECT * - 我不想在查詢中指定表標題(因爲有50多個表標題)。

+0

這種設計可能有合法的原因,但列舉的列經常暗示 – Strawberry 2014-12-07 09:39:24

回答

0

查找所有列的唯一方法是提及SQL查詢中的所有列。 這可能與一個做左連接的每一列,或者與相關子查詢:

SELECT (SELECT colB FROM Table2 WHERE colA = Table1.colA) AS colA, 
     (SELECT colB FROM Table2 WHERE colA = Table1.colB) AS colB, 
     (SELECT colB FROM Table2 WHERE colA = Table1.colC) AS colC, 
     ... 
FROM Table1 

不能使用SELECT *。如果您不知道Table1的列,可以從數據庫中讀取它們,並動態構建查詢。

相關問題