简体   繁体   中英

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 . 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 .

What happens to the rows from each of the tables when the 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 ?

该页面很好地解释了左右外部联接,我认为您应该看一下: 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:

Table1

tc1
0
1
2

and 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. 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.
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.
FULL will return all the rows from both sides.

When a match is not found on one side, the values are returned as 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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