我有3个表A,B和C.每个表都有一个ID和一个值字段。 我使用什么样的连接将这些连接合并到一个具有ID字段和列值A,值B,值C的表中?
当然,我只想在结果表中为每个ID记录1条记录。感谢。
示例:
表A:
1 x
2 y
表B:
2 a
3 b
表C:
2 m
我需要的结果:
1 x - -
2 y a m
3 - b -
答案 0 :(得分:2)
如果Ids分布在所有表中,请将它们组合在一起并对其进行分组/聚合:
SELECT Id, MAX(ValueA) AS ValueA, MAX(ValueB) AS ValueB, MAX(ValueC) AS ValueC
FROM (
SELECT Id, ValueA, NULL AS ValueB, NULL AS ValueC
FROM TableA
UNION ALL
SELECT Id, NULL AS ValueA, ValueB, NULL AS ValueC
FROM TableB
UNION ALL
SELECT Id, NULL AS ValueA, NULL AS ValueB, ValueC
FROM TableC
)
GROUP BY Id
如果每个Id都是唯一的,并且在每个表中都存在一次:
SELECT TableA.Id, TableA.ValueA, TableB.ValueB, TableC.ValueC
FROM TableA
INNER JOIN TableB ON TableA.Id = TableB.Id
INNER JOIN TableC ON TableA.Id = TableC.Id
如果每个Id都是唯一的,则存在于TableA中,并且在其他表中存在一次或不存在(不存在的值作为NULL
s提供):
SELECT TableA.Id, TableA.ValueA, TableB.ValueB, TableC.ValueC
FROM TableA
LEFT OUTER JOIN TableB ON TableA.Id = TableB.Id
LEFT OUTER JOIN TableC ON TableA.Id = TableC.Id
如果每个Id在TableA中唯一存在但在其他表中可能存在多次,请使用某种聚合,如MAX
或SUM
:
SELECT TableA.Id, MAX(TableA.ValueA) AS ValueA, SUM(TableB.ValueB) AS ValueB, MIN(TableC.ValueC) AS ValueC
FROM TableA
INNER JOIN TableB ON TableA.Id = TableB.Id
INNER JOIN TableC ON TableA.Id = TableC.Id
GROUP BY TableA.Id
答案 1 :(得分:1)
听起来你想要一个左连接。我还使用CTE从各种表中获取所有ID:
WITH ids as
(
SELECT id from table1
UNION
SELECT id from table2
UNION
SELECT id from table3
)
SELECT distinct ids.id, t1.col1, t2.col1, t3.col1
FROM ids
LEFT JOIN Table1 as t1
ON ids.id = t1.id
LEFT JOIN Table2 as t2
ON ids.id = t2.id
LEFT JOIN Table3 as t3
ON ids.id = t3.id
答案 2 :(得分:1)
以下代码使用FULL JOIN为每个ID返回一行,无论该ID是否存在于所有表中。
CREATE TABLE #A
( Id INT NOT NULL
, Value VARCHAR(10) NOT NULL);
CREATE TABLE #B
( Id INT NOT NULL
, Value VARCHAR(10) NOT NULL);
CREATE TABLE #C
( Id INT NOT NULL
, Value VARCHAR(10) NOT NULL);
INSERT INTO #A (Id, Value)
VALUES (1, 'x'), (2, 'y');
INSERT INTO #B (Id, Value)
VALUES (2, 'a'), (3, 'b');
INSERT INTO #C (Id, Value)
VALUES (2, 'm');
SELECT Id = COALESCE(a.Id, b.Id, c.Id)
, ValueA = a.Value
, ValueB = b.Value
, ValueC = c.Value
FROM #A a
FULL JOIN #B b
ON a.Id = b.Id
FULL JOIN #C c
ON a.Id = c.Id;