SQL multi-table query statement and subquery

In actual development, multi-table query is one of the very common requirements. The multi-table query statement of SQL can realize the associated query between multiple tables, and it is very flexible to use. The subquery is an extremely important query method in SQL, and the result of the subquery can be used as the condition or result of another query. This article will introduce in detail the multi-table query statements and subqueries in SQL, including inner join queries, outer join queries, self-join queries and different types of subqueries, to help readers better grasp the query syntax of SQL.

In terms of multi-table query, this article will introduce a variety of common query methods, including implicit inner join, explicit inner join, left outer join, right outer join, self-join, etc. Each query method will be equipped with detailed syntax and demonstration cases to help readers better understand and master. In terms of subqueries, this article will introduce in detail various types of subqueries such as scalar subqueries, column subqueries, row subqueries, and table subqueries, as well as their usage scenarios and grammar rules.

Whether it is the query requirements in daily development, or in the learning and use of SQL, multi-table query and subquery are very basic and important content. This article aims to help readers better understand and master SQL multi-table query statements and subqueries through detailed introductions and case demonstrations, and improve SQL query capabilities and application levels.

Multi-table query classification

  • connection query
    • Inner join: equivalent to querying the intersection data of A and B
    • Outer join:
      • Left outer join: Query all data in the left table, and some data in the intersection of two tables.
      • Right outer join: Query all the data in the right table, and the intersection data of the two tables.
    • Self-join: the connection query between the current table and itself, the self-join must use the table alias
  • subquery
    insert image description here

Join query - inner join

Inner join query syntax (inner join query is the intersection of two tables):

  • implicit inner join

    SELECT 字段列表 FROM1,2 WHERE 条件 ...;
    
  • Show Inner Links

    SELECT 字段列表 FROM1 [INNER] JOIN2 ON 连接条件 ...;
    
  • Inner join demo

    • Query the name of each employee and the associated department name (implicit inner join implementation)
    • Table structure: emp, dept
    • Join condition: emp.dept_id = dept.id
    select emp.name,dept.name from emp , dept where emp.dept_id = dept.id;
    
    • Query the name of each employee and the associated department name (explicit inner join implementation)
    • Table structure: emp, dept
    • Join condition: emp.dept_id = dept.id
    select e.name,d.name from emp e inner join dept d on e.dept_id = d.id;
    
    e和d是别名
    

Join query - outer join

Query syntax for outer joins

  • Left outer join (equivalent to querying all data in table 1 (left table) including data in the intersection of table 1 and table 2)

    SELECT 字段列表 FROM1 LEFT [OUTER] JOIN2 ON 条件 ... ;
    
  • Right outer join (equivalent to querying all data in table 2 (right table) including the intersection of table 1 and table 2)

    SELECT 字段列表 FROM1 RIGHT [OUTER] JOIN2 ON 条件 ... ;
    

insert image description here

  • Outer join demo

    • Query all the data in the emp table and the corresponding department information (left outer join)
    • Table structure: emp, dept
    • Join condition: emp.dept_id = dept.id
    select e.*,d.name from emp e left outer join dept d on e.dept_id = d.id;
    
    • Query all the data in the dept table and the corresponding employee information (right outer join)
    • Table structure: emp, dept
    • Join condition: emp.dept_id = dept.id
    select d.*,e.* from emp e right outer join dept d on e.dept_id = d.id;
    

join query - self join

Self-join query syntax (self-join query, which can be an inner join query or an outer join query)

SELECT 字段列表 FROM 表A 别名A JOIN 表A 别名B ON 条件...;

insert image description here

  • self-connect demo

    • Query the names of employees and their leaders
    • Table structure: emp
    select a.name,b.name from ema a ,emp b where a.managerid = b.id;
    
    • Query the name emp of all employees emp and their leaders. If the employee has no leader, it also needs to be queried
    • Table structure: emp.a, emp.b
    select a.nme '员工' , b.name '领导' from emp a left join emp b on a.managerid = b.id;
    

Union query - union, union all

For union queries, the results of multiple queries are combined to form a new query result set

Note: Must the number of columns and field types of multiple tables in the joint query be consistent.

union all will directly merge all the data together, and union will deduplicate the merged data

SELECT 字段列表 FROM 表A ...
UNION[ALL]
SELECT 字段列表 FROM 表B ...;
  • Query Demo

    • Query all employees whose salary is less than 5000 and employees whose age is greater than 50
    select * from emp where salary < 5000
    union all    //查询时如果需要去重则直接把all去掉即可
    select * from emp where age > 50;
    

subquery

Concept: nested SELECT statements in SQL statements are called nested queries, also known as subqueries.

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

SELECT * FROM t1 WHERE column1 = (SELECT column1 FROM t2);
  • According to different subquery results, it is divided into:

    • Scalar subquery (subquery result is a single value)
    • Column subquery (the result of the subquery is a column)
    • Row subquery (subquery result is one row)
    • Table subquery (the result of the subquery is multiple rows and multiple columns)
  • According to the position of the subquery, it is divided into: after WHERE, after FROM, and after SELECT.

scalar subqueries

The result returned by a subquery is a single value (number, string, date, etc.), in its simplest form, such a subquery is called a scalar subquery

Commonly used operators: = <> > = < < =

  • Query all employee information of "Sales Department"

    select * from emp where dept_id = (select id from dept where name = '销售部');
    

column query

The result returned by a subquery is a column (can be multiple rows), this subquery is called a column subquery.

Commonly used operators: IN, NOT IN, ANY, SOME, ALL

operator describe
IN Within the specified collection range, choose one more
NOT IN not within the specified collection
ANY In the list returned by the subquery, any one can satisfy
SOME Equivalent to ANY, ANY can be used wherever SOME is used
ALL All values ​​in the list returned by the subquery must satisfy
  • According to the department ID, query employee information (all employee information in the sales department and marketing department)
select * from emp where dept_id in (select id from dept where name = '销售部' or name = '市场部');
  • Query information about employees whose salary is higher than that of everyone in the finance department
select * from emp where salary > all (select salary from emp where dept_id = (select id from dept where name = '财务部'));
  • Query information about employees whose salary is higher than that of anyone in the R&D department
select * from emp where salary > any (select salary from emp where dept_id = (select id from dept where name = '研发部'));

row subquery

A subquery returns one row (can be multiple columns), this subquery is called a row subquery

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

  • Query the same employee information as 'Zhang San''s salary and immediate leadership
select * from emp where (salary,managerid) = (select salary,managerid from emp where name = '张三');

table subquery

The result returned by a subquery is multiple rows and multiple columns. This subquery is called a table subquery.

Commonly used operators: IN

  • Query employee information with the same position and salary as "Zhang San" and "Li Si"
select * from emp where (job,salary) in (select job,salary from emp where name = '张三' or name = '李四');

You can use the DISTINCT keyword to deduplicate query results.

In the SQL statement, you can use DISTINCTthe keyword to deduplicate the query results.

For example, to query the departments of all employees, you can use the following SQL statement:

SELECT DISTINCT dept_id FROM emp;

This will return a list of all the different department ids where each id appears only once.

Multi-table relationship (summary)

one-to-many Set the foreign key on the many side, and associate the primary key on the one side
many to many Create an intermediate table, the intermediate table contains two foreign keys, and associates the primary keys of the two tables
one to one For table structure splitting, set a foreign key (UNIQUE) on either side, and associate the primary key of the other side

Multi-table query (summary)

内连接
			隐式:SELECT...FROM 表A,表B WHERE 条件...
			显示:SELECT...FROM 表A INNER JOIN 表B ON 条件...

外连接
			左外:SELECT...FROM 表A LEFT JOIN 表B ON 条件...
			右外:SELECT...FROM 表A RIGHT JOIN 表B ON 条件...

自连接:SELECT...FROM 表A 别名1,表A 别名2 WHERE 条件...

子查询:标量子查询、列子查询、行子查询、表子查询

Guess you like

Origin blog.csdn.net/weixin_43472938/article/details/129543528