MySQL multi-table query (joint query, join query, subquery)

Table of contents

Multi-table joint query

Union query type

Multi-table join query

Classification of multi-table queries

Cross query (Cartesian product)

inner join query

Outer join query

self join query

subquery rules

Classification of Subqueries

Different results for subqueries

EXISTS和NOT EXISTS

Different places where subqueries are applied

Application of subqueries in different external statements


Multi-table joint query

1. Through joint query, you can get the set of records in two tables or the set of common records, or the set of records in one of the tables

2. The joint query operates on the table in units of rows, mainly to increase or decrease the number of rows

3. The number of columns and the type of the number of columns between multiple tables used as a joint query must be the same (for example: which columns are queried in table 1, which columns are queried in table 2)

4. The joint query will remove duplicate records by default

5. The joint query can use any SELECT statement, but the ORDER BY clause can only be used at the last time

Union query type

UNION adds records of certain fields of two tables (union)

ALL is used as a keyword, indicating that the result of the set operation retains duplicate rows (generally UNION ALL)

INTERSECT extracts (intersection) common records of some fields of two tables (MySQL does not exist, you can use the following connection query instead)

EXCEPT subtracts the common records of some fields of the two tables, and then returns the remaining records (difference set) of a table (MySQL does not exist, use the NOT IN field to achieve)

Union query format

Union format

SELECT field list FROM table A ...   UNION SELECT field list FROM table B ...;

Return the union of table A query and table B query (and deduplicate processing)

Union all format

Compared with Union query, this query can not deduplicate the merged data

Union Query Demo

We use the following two tables for demonstration

select name , age from staff1 where origo = ' Chongqing ' union select name , age from user;   # query table 1 origo is the name of Chongqing , the result of the age field plus the result of table 2 query name , age , and deduplication processing ( The name and age data types of the two tables are required to be consistent)

select name , age from staff1 where origo = ' Chongqing ' union all select name , age from user; #No deduplication processing

select name , age from staff1 where ( name , age ) not in ( select name , age from user ) #Query the difference between table 1 and table 2 (subtract the intersection of table 1 and table 2 from the query result of table 1 )


Multi-table join query

Multi-table query is based on horizontal columns, mainly adding some columns of other tables

When performing multi-table queries, the columns in the SELECT clause are generally written in the format of table name alias.column name

We use two tables for demonstration

Classification of multi-table queries

cross query

       Combining all the records of the two tables, the number of records obtained is the product of the number of rows in the two tables

inner join query

Query the data in the intersection of tables A and B

Outer join query

       Left outer join: query all the data in the left table, and the data in the intersection of the two tables

       Right outer join: query all the data in the right table, and the data in the intersection of the two tables

self join query

There is only one table, and the current table is connected to itself (the sub-join must use the alias of the table)

Cross query (Cartesian product)

Cross joins are done using the set operator GROSS JOIN (Cartesian product)

Cross-combining all the records of the two tables, while adding other table fields, the number of records obtained is the product of the number of rows in the two tables

Format

SELECT field list FROM table 1, table 2; the displayed data volume is the data volume of table 1 * the data volume of table 2

Precautions

We can see through the phenomenon that there are too many results and there are errors, there is not much practical value, and it takes a lot of computing time; so this query will not be used in actual business

But this query is the basis for all table queries

select user . name , career. name from user , career ;   #No aliases are used 
select u. name , c. name from user u , career c #Use aliases for cross query

inner join query

Data that exists in both tables can be selected, that is, the intersection data of the two tables

Divided into implicit inner connection and explicit inner connection, the two are just written differently, and the results obtained are exactly the same

implicit inner join

SELECT field list FROM table 1, table 2 WHERE condition list;

explicit inner join

SELECT field list FROM table 1 [INNER] JOIN table 2 ON connection condition list [WHERE judgment statement] ;

INNER can be omitted

If you want to add Where to this statement, you need to pay attention that the ON statement must be between FROM and WHERE

The execution sequence is: first display the inner connection, and then perform Where on the result of the connection

Precautions

There may be missing data using inner joins, and NULL values ​​will be missed

select u. name , u. age , c. name from user u , career c   where u. career_id = c. id #implicit query; select the records with the same user.career_id and career.id , and display the corresponding records The user.name , user, age , career.name fields; at this time, if user.career_id has a null value or career.id has a null value, the data corresponding to the null value will be missed (at this time, the sixth The data)
select u. name , u. age , c. name from user u join career c   on u. career_id = c. id #explicit query; the results of the two queries are as follows

select u. name , u. age , c. name from user u join career c   on u. career_id = c. id where u. age > 20 #Explicit query to filter the above results, select the data whose age is greater than 20

Outer join query

Select all the information of a single table (main table), and then add the information of the intersection of the two tables

left outer join

SELECT field list FROM table 1 LEFT [OUTER] JOIN table 2 ON condition list;

[OUTER] can be omitted

Query all the data in table 1, including the data in the intersection of table 1 and table 2

select u. name , u. age , c. name from user u left join career c on u. career_id = c. id ; #Left outer join displays all the information of the corresponding name and age fields of the user table , and then adds user. The intersection of career_id and career.id

right outer join

SELECT field list FROM table 1 RIGHT [OUTER] JOIN table 2 ON condition list;

[OUTER] can be omitted

Query all the data in table 2, including the data in the intersection of table 1 and table 2

select u. name , u. age , c. name from user u right join career c on u. career_id = c. id ; #The right outer join displays all the information of the corresponding name section of the career table , and then adds user.career_id and Intersection of career.id

self join query

Use this table to do a demonstration of self-join query (this table records the ID table of employees and their corresponding supervisors—that is, the name of the id corresponding to managerid is the name of the supervisor)

Connect yourself to query by yourself, which can be an inner connection or an outer connection

Format

SELECT field list FROM table A alias A JOIN table A alias B ON condition list;

select e1.name , e2.name ' supervisor from emp e1 join emp e2 on e1.managerid = e2.id ; #Display   query , query who is the supervisor corresponding to each employee; it can be understood as copying emp as table e1 and Table e2 has two tables, associate the managerid of e1 table with the id of e2 as a foreign key , and then display the name of e1 table and the name of e2 table (here, there will be omissions when using explicit inner join method)  
select e1.name , e2.name ' Boss ' from emp e1 left join   emp e2 on e1.managerid = e2.id ; #Left outer connection, employees without leaders are also displayed


subquery rules

A subquery (Sub Query) can also be called a nested query, which is a query nested in the Where clause of other SQL queries; a statement containing a subquery is called an external statement

  1. Subqueries must be enclosed in ()
  2. Generally, the SELECT statement of a subquery has only one field, unless there are multiple columns in the outer statement that need to be compared with the columns of the subquery
  3. Subqueries cannot be directly applied to aggregate functions, and subqueries cannot use ORDER BY
  4. Ntext, text, and image data types cannot be used in the select list of a subquery
  5. The keyword DISTINCT cannot be used with subqueries containing GROUP BY

Classification of Subqueries

According to the different results of the subquery, it can be divided into 4 categories

scalar subquery subquery results as a single value

Column subquery The result of the subquery is one column and multiple rows

Row subquery The subquery result is one row with multiple columns

Table subquery The result of the subquery is multiple rows and multiple columns

According to the different positions of the subquery, it can be roughly divided into three categories

There are three main cases where subqueries apply:

They are after WHERE, after FROM, and after SELECCT

According to the different external statements of the subquery, it can be roughly divided into four categories

Statements outside the subquery can be

Any of INSERT / UPDATE / DELETE / SELECT

Different results for subqueries

Query through the following two tables

Scalar subquery - the query result must only return one row and one column of results, that is, a certain value

Since the result of its subquery is a single value, it can be used to perform arithmetic operations

Common operators: = , <> , > , >= , < , <=

select * from emp where dept_id =( select id from dept where name = ' sales department ' ) ; #Query all employees corresponding to the sales department (first query the id corresponding to the sales department , and then query the employees according to the id) select * from emp where entrydate >= ( select entrydate from emp where name = ' Zhang San ' ) ; #Query all employee information after Zhang San's entry (first query Zhang San's entry information, and then query the employee information after this time

Column subquery - the return result is one column with multiple rows

Commonly used operators:

IN Select one from the set range specified by IN

NOT IN is not within the specified set range

Any one of the ANY subquery return list is sufficient

SOME is equivalent to ANY

All values ​​in the list returned by the ALL subquery must satisfy

select * from emp where salary > all ( select salary from emp where dept_id =( select id from dept where name = ' R & D department ' )) ; #Query the employee information whose salary is higher than that of all financial employees (first query the financial department corresponding id , use this id to query the salary of employees in the financial department, and then find out the information of employees whose salary is greater than this)

Row subquery - the return result is one row with multiple columns

Common operators: =, <>, IN, NOT IN

select * from emp where ( salary , managerid ) = ( select salary , managerid from emp where name = ' Li Si ' ) ; #Query the information of other employees with the same salary and leadership as Li Si

Table subquery - the return result is multiple rows and multiple columns

Commonly used operators: IN

often appears after from

select * from emp where ( dept_id , salary ) in ( select dept_id , salary from emp where name = ' Old Five ' or name = ' Li Si ' ) ;  #query for other employees who have the same department and same salary as Lao Wu or Li Si Employee information 

select e.* , dept. name from ( select * from emp where entrydate > '2001-01-01' ) eleft join dept on e.dept_id = dept.id ; #Query employee information and corresponding department information whose entry time is greater than 2001-01-01

EXISTS和NOT EXISTS

The format is: EXISTS (subquery)

EXISTS is used to check whether the subquery returns at least one row of data; if the subquery returns at least one row of data, it is True; if the subquery does not return data, it is False

In some cases, IN or ANY fields can also be used instead

NOT EXISTS is the opposite of EXIST

select * from emp where exists ( select * from emp where id = 10 ) ; #As long as there is a value of id=10 , query the emp table and the result is no data
 select * from emp where exists ( select * from emp where id = 1 ) ; #As long as there is a value of id=1 , query the emp table and the result is the emp table data

Different places where subqueries are applied

There are three main situations where the subquery is applied: after WHERE, after FROM, and after SELECCT

In the Where clause - general subqueries are applied after where

What we have demonstrated above are all subqueries after where

Generally formal: SELECT * FROM t1 WHERE column1= ( SELECT column1 FROM t2 );

In the From clause - the result set returned by the subquery at this time will be used as a temporary table, which is also called a derived table

The derived table must be configured with an alias, and the column names of the derived table must be unique

select * from 
     ( select origo , count ( * ) as number from staff1 group by origo ) as emp 
     where emp.number > 2 ; #Group by place of residence, and query the number of people in place of residence greater than 2 (the alias of the derived table is emp)

After Select - only scalar subquery is supported, the subquery returns a single value

SELECT (subquery) FROM table1;

The single value returned by the subquery is a field in Table 1; this query is rarely used

Application of subqueries in different external statements

The statement outside the subquery can be any one of INSERT/UPDATE/DELETE/SELECT

Experiments based on the following two tables

Subquery in SELECT statement

select * from user where career_id =( select id from career where name = ' chef ' ) ; #query who is a chef in user (subquery query chef id , and then external statement to query the person corresponding to this id )

Subqueries in INSERT statements

insert into user1 ( name , age , career_id ) 
     select * from user 
     where career_id in ( select id from career) ; #Add data to the user1 table, the added data is the person with a position in the user table

Subqueries in UPDATE statements

update user set age = age * 1.5 where career_id = ( select id from career where name = ' chef ' ) ; #multiply the chef's age by 1.5

Subquery in DELETE statement

delete from user where career_id = ( select id from career where name = ' chef ' ) ; #Explain the information that the occupation in the user table is a chef

Guess you like

Origin blog.csdn.net/m0_49864110/article/details/131944306