[MySQL] Outer join query

If we 内连接query the data using:

Use inner join - onclause: display all matching information

select * 
from emp e
inner join dept d
on e.deptno = d.deptno;

insert image description here

inner join - onClause disadvantages:

  1. If the department number is 40, no employee information is displayed, and it will not be displayed in the query
  2. An employee does not have department number information and will not be displayed in the query

Therefore, if you use an inner connection to query, sometimes the displayed data is incomplete . If we want to display information that does not match in the two tables, we can use 外连接a query.

Outer joins include:

  • Left outer join :left outer join
  • Right outer join :right outer join

PS : In the process of using,outerit can be omitted.

Using the left outer join, the information of the table on the left can display the data even if it does not match;
using the right outer join, the information of the table on the right can display the data even if it does not match.

Full outer join :full outer join

This syntax will display all mismatched data in the left and right tables , but mysqlit is not supported in , but oracleit is supported in .

select *
from emp e
full outer join dept d
on e.deptno = d.deptno;

Returns a 1064 syntax error:

1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘full outer join dept d
on e.deptno = d.deptno’ at line 3

unionHowever, this logic can be implemented using syntax , and the keyword unionrepresents the union of the left and right outer join queries.

1. Using unionfetch union will automatically deduplicate , so the efficiency is low .

select *
from emp e
left outer join dept d
on e.deptno = d.deptno
union -- 并集-去重-效率低
select * 
from emp e
right outer join dept d
on e.deptno = d.deptno;

2. union allThe union is used without deduplication , so the efficiency is high .

select *
from emp e
left outer join dept d
on e.deptno = d.deptno
union all -- 并集-不去重-效率高
select * 
from emp e
right outer join dept d
on e.deptno = d.deptno;

mysqlThe support for set operations is weak, only union operations are supported, intersection and difference operations are not supported ( oraclemedium is supported).

Guess you like

Origin blog.csdn.net/hold_on_qlc/article/details/130460584