我有2个表:表1 和表2 :
ID 列 Table1 和 Table2
表1 的 ID 比表2
更多但我希望有一个查询能够将 Table1 的所有 ID 返回给 Table2
的第3列>+------+-------+
| Id | Col2 |
+------+-------+
| 1 | 20000 |
| 2 | 20001 |
| 3 | 20002 |
| 4 | 20003 |
+------+-------+
+------+------+------+
| Col1 | Id | Col3 |
+------+------+------+
| 100 | 1 | 25 |
| 100 | 2 | 50 |
| 100 | 4 | 40 |
+------+------+------+
我希望有这张表:
+------+-------+--------+
| Col1 | Col2 | Col3 |
+------+-------+------+-+
| 1 | 20000 | 25 |
| 2 | 20001 | 50 |
| 3 | 20002 | 0 |
| 4 | 20003 | 40 |
+------+-------+------+-+
答案 0 :(得分:1)
如果你想要这个“但我希望有一个查询,它返回Table1的所有Id和Table2的第3列”:
select t1.id, t2.Col3 from table1 t1 left join table2 t2 on t1.id = t2.id
如果你想得到表3:
select t1.id as Col1, t1.Col2, COALESCE(t2.Col1, 100) as Col3, COALESCE(t2.Col3, 0) as Col4
from table1 t1 left join table2 t2 on t1.id = t2.id
答案 1 :(得分:1)
Oracle 11g R2架构设置:
CREATE TABLE Table1 ( Id, Col2 ) AS
SELECT 1, 20000 FROM DUAL
UNION ALL SELECT 2, 20001 FROM DUAL
UNION ALL SELECT 3, 20002 FROM DUAL
UNION ALL SELECT 4, 20003 FROM DUAL;
CREATE TABLE Table2 ( Col1, Id, Col3 ) AS
SELECT 100, 1, 25 FROM DUAL
UNION ALL SELECT 100, 2, 50 FROM DUAL
UNION ALL SELECT 100, 4, 40 FROM DUAL;
查询1 :
SELECT t1.Id,
Col2,
COALESCE( Col1, 100 ) AS Col1,
COALESCE( Col3, 0 ) AS Col3
FROM Table1 t1
LEFT OUTER JOIN
Table2 t2
ON ( t1.Id = t2.Id )
<强> Results 强>:
| ID | COL2 | COL1 | COL3 |
|----|-------|------|------|
| 1 | 20000 | 100 | 25 |
| 2 | 20001 | 100 | 50 |
| 4 | 20003 | 100 | 40 |
| 3 | 20002 | 100 | 0 |