0

我有两张桌子。

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?

4

1 回答 1

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 |
于 2013-04-05T20:40:56.870 回答