用于连接两个表的Sql Query获取具有以下结果的数据

时间:2016-02-15 10:12:55

标签: sql-server database

Heloo,

我有2个表表1和表2有很多关系,两个表都有外键RecID。

Table
 ID  Amount  RecID
 1   100     10
 2   300     4
 3   400     5
 4   500     5

Table 2
ID Amount RecID
1  50     10
2  50     10
3  300    4
4  900    5

我需要连接两个表来获取这两个表中的所有行。

Result Table
AmountTable 1   RecIDTable1  AmountTable2  RecIDTable2
100             10           50            10 
Null            Null         50            10
300             4            300           4
400             5            900           5
500             5            Null          Null

2 个答案:

答案 0 :(得分:0)

注意:我在OP将MySQL和SQL Server都指定为标记时发布了这个答案。

您正尝试对两个表执行完全外连接。由于MySQL中没有FULL OUTER JOIN,因此您必须以其他方式实现它。一种方法是在两个表之间进行左右连接UNION

SELECT t1.Amount AS AmountTable1, t1.RecID AS RecIDTable1,
    t2.Amount AS AmountTable2, t2.RecID AS RecIDTable2
FROM t1
LEFT JOIN t2 ON t1.id = t2.id AND t1.RecID = t2.RecID
UNION
SELECT t1.Amount AS AmountTable1, t1.RecID AS RecIDTable1,
    t2.Amount AS AmountTable2, t2.RecID AS RecIDTable2
FROM t1
RIGHT JOIN t2 ON t1.id = t2.id AND t1.RecID = t2.RecID

请按照以下链接查看正在运行的演示:

SQLFiddle

答案 1 :(得分:0)

正如您在问题中提到的SQL-Server标记。所以这是使用Full Outer Join这样的查询 -

SELECT
    t1.Amount AS AmountTable1
    ,t1.RecID AS RecIDTable1
    ,t2.Amount AS AmountTable2
    ,t2.RecID AS RecIDTable2
FROM @tab1 t1
FULL JOIN @tab2 t2
    ON t1.RecID = t2.RecID