SQL 加入空表以返回所有行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5380929/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 09:47:19  来源:igfitidea点击:

Joining empty table to return all rows

sqlsql-serversql-server-2005tsql

提问by Scorpion

I have a table (Table1) which has a composite primary key(Column1 + Column2). I am using it as a foreign key in another table (Table2).

我有一个表(Table1),它有一个复合主键(Column1 + Column2)。我将它用作另一个表(表 2)中的外键。

Now I want to a SELECT statement to select all records from Table1 and Table2. But its returning me 0 rows, because table2 is Empty. I want all records from table1 and if it does not exist in table2, value of Columns in Table2 should be null.

现在我想要一个 SELECT 语句来从 Table1 和 Table2 中选择所有记录。但它返回给我 0 行,因为 table2 是空的。我想要 table1 中的所有记录,如果 table2 中不存在,则 Table2 中 Columns 的值应为空。

I know, I only need to Join it. But I am not getting it right.

我知道,我只需要加入它。但我没有做对。

Thanks

谢谢

回答by Hallaghan

SELECT * FROM Table1 T1
LEFT JOIN Table2 T2 ON T1.Id = T2.FK

FK is your foreign key on the second table. A Left Join will return all rows from table1 even if they don't exist in table2.

FK 是您在第二张桌子上的外键。左连接将返回 table1 中的所有行,即使它们在 table2 中不存在。

回答by Martin Smith

You need an outer join

你需要一个外连接

SELECT *
FROM   table1
       LEFT OUTER JOIN table2
         ON table1.column1 = table2.column1
            AND table1.column2 = table2.column2  

Leftmeans preserve all rows from the left (first) table in the query.

Left表示保留查询中左侧(第一个)表中的所有行。

回答by Shaded

You need a LEFT JOIN

你需要一个 LEFT JOIN

SELECT Table1.*, Table2.*
FROM Table1
LEFT JOIN Table2 ON Table1.Column1 = Table2.Column2

Try that out.

试试看。

回答by malinois

Use LEFT JOINfor join you tables. See SQL SERVER JOINS to understand the concept.

使用LEFT JOIN了加入你的表。请参阅SQL SERVER JOINS以了解该概念。