MySQL multi-table queries Study Notes

 

First, the case ready  

create table dept(
id int primary key auto_increment,
name varchar(20)
);
View Code
INSERT  INTO the dept values ( null , ' Ministry of Finance ' );
 INSERT  INTO the dept values ( null , ' Personnel Department ' );
 INSERT  INTO the dept values ( null , ' Science and Technology ' );
 INSERT  INTO the dept values ( null , ' Sales ' );
View Code
create table emp(
id int primary key auto_increment,
name varchar(20),
dept_id int
);
View Code
INSERT  INTO EMP values ( null , ' John Doe ' , . 1 );
 INSERT  INTO EMP values ( null , ' John Doe ' , 2 );
 INSERT  INTO EMP values ( null , ' Wang ' , . 3 );
 INSERT  INTO EMP values ( null , ' Liu can ' , 5 );
View Code

Demand : check out the information department employee information and the corresponding departments

Second, a Cartesian product of the query, the query is connected, and the left and right outer join queries full outer join query

① Cartesian product inquiry

Two tables obtained by multiplying out the results: select * from dept, emp;

If the table has left records m, n have the right records, then check out the result is m * n pieces. These results included a large number of erroneous results, do not usually use this query.

Join queries within ②

Table on the left and right of the table there is also some records

SQL:select * from dept d inner join emp e on e.dept_id=d.id;

③ left outer join query: basic inner join queries on the table plus the left and right of the table there is no record

Check out employee information corresponding to the department, while those who are not employees of the department are listed

SQL:select * from dept d left join emp e on e.dept_id=d.id;

④ right outer join query: query, including on the basis of connection, plus the right and left of the table table has no records

Check out employee information corresponding to the department, while those who do not list the staff department

SQL:select * from dept d right join emp e on e.dept_id=d.id;

⑤ full outer join query: basic inner join queries on the table plus the left and right of the table there are no records left and right of the table and the table has no records.

  Check out employee information corresponding to the sector, while the list of employees who do not have the staff departments and some departments do not

SQL: select * from dept d full join emp e on e.dept_id = d.id; ( Error: mysql does not support full outer join query )

  To simulate the full outer join query by keyword union

SQL

select * from dept left join emp on emp.dept_id = dept.id
union
select * from dept right join emp on emp.dept_id = dept.id;

 

Guess you like

Origin www.cnblogs.com/rmxd/p/11416328.html