简体   繁体   English

SQL左联接查询结果行

[英]SQL Left Join Query Result Row

When you perform a left join on two tables let's say teacher and department ON teacher.id = department.id . 当您在两个表上执行左联接时,假设教师和部门ON teacher.id = department.id Left join will compare each record from the left table (teacher) with each record from the right table (department) and join the record into a result row if the teacher.id = department.id . 左联接会将左表(教师)中的每个记录与右表(部门)中的每个记录进行比较,如果teacher.id = department.id则将记录teacher.id = department.id到结果行中。

What happens to the rows from each of the tables when the teacher.id != department.id ? teacher.id != department.id时,每个表中的行会发生什么? Do the rows from the teacher and department table still get joined into one result row except each column value for the result row will have a value of NULL ? 教师和部门表中的行是否仍合并到一个结果行中,除了结果行的每一列值都将具有NULL

该页面很好地解释了左右外部联接,我认为您应该看一下: http : //blog.codinghorror.com/a-visual-explanation-of-sql-joins/

For a clear explanation on how Left & Right joins work, and the results they may produce, check these: 要明确了解左右联接的工作方式以及它们可能产生的结果,请检查以下各项:

Left joins explained. 左联接说明。

Right joins explained. 右连接说明。

Hope it helps. 希望能帮助到你。

Suppose we have 2 tables: 假设我们有2个表:

Table1

tc1
0
1
2

and Table2 和表Table2

tc2
0
2
3

This would be the result from the various queries on these 2 tables 这将是对这两个表的各种查询的结果

SELECT tc1, tc2 FROM table1, table2 WHERE tc1=tc2

Result: 结果:

tc1  tc2
0    0
2    2

This is the same as this query: 此查询与此相同:

SELECT tc1, tc2 FROM table1 INNER JOIN table2 ON tc1=tc2

It basically returns only the rows where tc1=tc2. 它基本上只返回tc1 = tc2的行。 Simple. 简单。 Now outer joins behave differently. 现在,外部联接的行为有所不同。 They include all the rows from one table. 它们包括一个表中的所有行。
LEFT means it will include all the rows from the set that you already have, even if they don't match anything in the joined table. LEFT表示它将包括集合中所有行,即使它们与联接表中的任何内容都不匹配。
RIGHT means that it will include all rows from the joined table, even if they don't match anything in the rows you already have. RIGHT表示它将包括联接表中的所有行,即使它们与您已有的行中的任何内容都不匹配。
FULL will return all the rows from both sides. FULL将从两侧返回所有行。

When a match is not found on one side, the values are returned as NULL 如果在一侧找不到匹配项,则将这些值返回为NULL

SELECT tc1, tc2 FROM table1 LEFT JOIN table2 ON tc1=tc2

the result will be: 结果将是:

tc1  tc2
0    0
1    NULL
2    2

Now, with right join 现在,有了正确的加入

SELECT tc1, tc2 FROM table1 RIGHT JOIN table2 ON tc1=tc2

will return 将返回

tc1  tc2
0    0
2    2
NULL 3

And now, full outer join 现在,完全外部联接

SELECT tc1, tc2 FROM table1 FULL OUTER JOIN table2 ON tc1=tc2

will return all the rows, with matching nulls 将返回所有行,并匹配null

tc1  tc2
0    0
1    NULL
2    2
NULL 3

Keep in mind, that these are equivalent: 请记住,这些是等效的:

INNER JOIN        <=>  JOIN
LEFT OUTER JOIN   <=>  LEFT JOIN
RIGHT OUTER JOIN  <=>  RIGHT JOIN

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM