SQL查询使用第二个查找表解码表

时间:2014-12-07 09:35:25

标签: mysql sqlite

我有两个表 - 表1的整数和表2的字符串。

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多个表格标题)。

1 个答案:

答案 0 :(得分: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的列,则可以从数据库中读取它们,并动态构造查询。