我有两张桌子。
Table 1
+----+--------+
| Id | Column |
+----+--------+
| 1 | 23 |
+----+--------+
| 2 | 34 |
+----+--------+
| 3 | 99 |
+----+--------+
Table 2
+----+--------+
| Id | Column |
+----+--------+
| 10 | 1 |
+----+--------+
| 11 | 1 |
+----+--------+
| 21 | 2 |
+----+--------+
| 33 | 3 |
+----+--------+
我想将这些表组合起来获取
Table 3 (Desired)
+--------+--------+
| Column | Column |
+--------+--------+
| 10 | 23 |
+--------+--------+
| 11 | 23 |
+--------+--------+
| 21 | 34 |
+--------+--------+
| 33 | 99 |
+--------+--------+
我知道如何得到这个:
Table 3 (Actual)
+--------+--------+
| Column | Column |
+--------+--------+
| 10 | 23 |
+--------+--------+
| 11 | null |
+--------+--------+
| 21 | 34 |
+--------+--------+
| 33 | 99 |
+--------+--------+
但是当行有重复的Id列时,第一个是正确的值和 其余的总是NULL。
我必须生成表3的查询是
SELECT table2.id, table1.Column
FROM table2
LEFT JOIN (SELECT .... ) as table1 ON table1.id = table2.Column
如何连接表以获取表3的正确版本?
答案 0 :(得分:1)
这应该可以正常工作:
SELECT
t2.id AS column1,
t1.column AS column2
FROM table2 AS t2
LEFT JOIN table1 AS t1 ON t1.id = t2.column;
请在此处查看:
这将为您提供所需的相同结果:
| COLUMN1 | COLUMN2 |
---------------------
| 10 | 23 |
| 11 | 23 |
| 21 | 34 |
| 33 | 99 |