SQL language --- data query


foreword

This article mainly explains the relevant syntax of data query in SQL language, and gives detailed examples for readers' reference


1. Data query in SQL language

1. SELECT statement format

(1) Define the format

SQL设计了 S E L E C T − F R O M − W H E R E SELECT-FROM-WHERE SELECTFROMThe sentence structure of W H ERE
: SELECT A 1 , . . . , A n FROM R 1 , . . . , R m WHERE F where R 1 . . . is a relation, F is a formula, A 1 , . . . is Attribute SELECT \ A_1,...,A_n\\ FROM \ R_1,...,R_m\\ WHERE \ F\\ Here R_1...is a relation, F is a formula, A_1,...is an attribute\\SE L ECT A 1,...,AnFROM R 1,...,RmWHERE FHere R1... is a relation, F is a formula, A1,... is an attribute
simple understanding

  • A represents the information you want to query
  • R represents which relational data tables the information comes from
  • F represents the mathematical description of the collection operations required to obtain these data

(2) Grammatical statement of the conditional expression F in the WHERE clause

The following operators can be used in the conditional expression F of the WHERE clause

  • Arithmetic comparison operators: <, <= , > , >= , <> , !=
  • Logical operators: AND, OR, NOT
  • Set membership operators: IN, NOT IN
  • 谓词:EXISTS、ALL、SOME、UNIQUE
  • Aggregate functions: AVG, MIN, MAX, SUM, COUNT
  • The operand in F can also be another SELECT statement, that is, the SELECT sentence type can be nested
    insert image description here

(3) Grammatical format of the SELECT statement

The full syntax is as follows:

SELECT 目标表的列名或列表达式序列
FROM 基本表名和(或)视图序列
[WHERE 行条件表达式]
[GROUP BY 列名序列[HAVING 组条件表达式]]
[ORDER BY 列名[ASC|DESC],...]

Simple can be understood as:

  • SELECT clause: specify the attribute columns to display
  • FROM clause: specify the query object (basic table or view)
  • WHERE clause: specify query conditions
  • GROUP BY clause: Group the query results by the value of the specified column, and the tuples with equal column values ​​of this attribute are a group. Typically an aggregate function is applied to each group.
  • HAVING phrase: Only groups that meet specified conditions are output
  • ORDER BY clause: Sort the query result table in ascending or descending order of the specified column values

2. Single table query

(1) What is a single-table query?

A single-table query involves only one table and is the simplest query operation.
It has many uses as follows:

1.选择表中的若干列
2.选择表中的若干元组
3.对查询结果排序
4.使用聚合函数
5.对查询结果分组 

(2) Illustrate grammar with examples

Example 1: Simple query

Query the amount of tax that each person needs to pay, assuming that the salary above 800 needs to pay tax, and the tax rate is 10%
insert image description here
code:

SELECT ENAME,(SAL-800)*0.1 FROM EMP; 

result:
insert image description here

Example 2: Using an alias based on Example 1

insert image description here
code:

SELECT ENAME 姓名,SAL 薪水(SAL-800)*0.1 税金 FROM EMP;

insert image description here

Example 3: DISTINCT keyword

Use the DISTINCT keyword to achieve the effect of canceling duplicate rows

SELECT DEPTNO FROM EMP;

The default is ALL by default

SELECT ALL DEPTNO FROM EMP;

insert image description here

SELECT DISTINCT DEPTNO FROM EMP;

insert image description here

Example 4: Take a value within a range

SELECT ENAME ,SAL FROM EMP WHERE SAL BETWEEN 1500 AND 2000; 
``````sql
SELECT ENAME ,SAL FROM EMP WHERE SAL>=1500 AND SAL<=2000;

The two codes have the same effect, that is, BETWEEN AND is equivalent to >=AND<=.
insert image description here

Example 5: Determining a value in a collection

Two methods are provided below, both of which can find out the value of a specific collection element
Among them, * means that all columns are displayed, which is a default

SELECT * FROM EMP WHERE JOB IN('SALESMAN','CLERK');

insert image description here

SELECT * FROM EMP WHERE JOB='SALESMAN' OR JOB='CLERK';

insert image description here

Example 6: Character matching

Predicate: [NOT] LIKE '<matching string>' [ESCAPE '<escape character>']
<matching string> can be a complete string or containWildcards % and _

  • % (percent sign) represents a string of any length (the length can be 0)
    For example, a%b represents a string of any length starting with a and ending with b
  • _ (underscore) represents any single character.
    For example, a_b means any string of length 3 starting with a and ending with b

Query the names of employees whose names start with S and whose third letter is O

SELECT ENAME FROM EMP WHERE ENAME LIKE 'S_O%';

insert image description here

Example 7: ORDER BY clause

Can be sorted by one or more attribute columns
Ascending: ASC; Descending: DESC; default is ascending

When the sort column contains null values

  ASC:排序列为空值的元组最后显示
  DESC:排序列为空值的元组最先显示
SELECT * FROM EMP ORDER BY COMM ASC;

insert image description here

SELECT * FROM EMP ORDER BY COMM DESC;

insert image description here

Example 8: Aggregate functions

An aggregate function is another type of operation involving the entire relationship. Through an aggregate function, the values ​​in a column can be formed into a single value.
There are 5 main types of aggregation functions:

  • count
    COUNT([DISTINCT|ALL] *)
    COUNT([DISTINCT|ALL] <column name>)
  • Calculate sum
    SUM([DISTINCT|ALL] <column name>)
  • Compute average
    AVG ([DISTINCT|ALL] <column name>)
  • Find the maximum value
    MAX ([DISTINCT|ALL] <column name>)
  • Find the minimum value
    MIN ([DISTINCT|ALL] <column name>)
SELECT count(*) FROM EMP;

insert image description here

SELECT SUM(SAL) FROM EMP;

insert image description here

SELECT AVG(SAL) FROM EMP;

insert image description here

SELECT MAX(SAL) FROM EMP;

insert image description here

SELECT MIN(SAL) FROM EMP;

insert image description here

Example 9: GROUP BY clause

The object of the thinning set function

  • The query result is not grouped, the aggregate function will act on the entire query result
  • After grouping query results, aggregate functions are applied to each group separately
SELECT DEPTNO,AVG(SAL) AS 平均工资 FROM EMP GROUP BY DEPTNO;

insert image description here

Example 10: HAVING statement

Notice:
Aggregate functions cannot be used as conditional expressions in the WHERE clause, so HAVING phrases are required

Only groups that satisfy the conditions specified by the HAVING phrase are output.
The difference between the HAVING phrase and the WHERE clause: the object of action is different

  • The WHERE clause acts on a base table or view, from which tuples that satisfy the condition are selected.
  • The HAVING phrase acts on groups, from which the group that satisfies the condition is selected.

Check the departments whose average salary is more than 2200 yuan

SELECT DEPTNO ,AVG(SAL) AS 员工工资 FROM EMP GROUP BY DEPTNO HAVING AVG(SAL)>2200;

insert image description here

3. Connection query

(1) What is a join query?

Join query : a query that involves more than two tables at the same time
Join condition or join predicate : a condition used to join two tables
General format:
[<table name 1>.]<column name 1> <comparison operator> [<table name2>.]<column name2>
[<table name1>.]<column name1> BETWEEN [<table name2>.]<column name2> AND [<table name2>.]<column name3 >
Join fields : column names in the join predicate
The types of each join field in the join condition must be comparable, but the names do not have to be the same

(2) Explain with examples

Example 1: Equivalent join

View doctors and their corresponding titles according to their salaries
(DOCTOR_INFORMATION)
insert image description here

(DOCTOR_LEVEL)
insert image description here

SELECT DOCTOR_INFORMATION.*,DOCTOR_LEVEL.*
FROM DOCTOR_INFORMATION,DOCTOR_LEVEL
WHERE DOCTOR_INFORMATION.DOCTORSAL=DOCTOR_LEVEL.DLEVELSAL;

result:
insert image description here

Example 2: Inner join

View doctors and their corresponding titles according to their salaries
(DOCTOR_INFORMATION)
insert image description here

(DOCTOR_LEVEL)
insert image description here

SELECT DOCTOR_INFORMATION.*,DOCTOR_LEVEL.*
FROM DOCTOR_INFORMATION
INSERT JOIN DOCTOR_LEVEL
ON (DOCTOR_INFORMATION.DOCTORSAL=DOCTOR_LEVEL.DLEVELSAL);

Example 3: Natural Joins

A natural join means that when retrieving multiple tables, Oracle will automatically join the columns in the first table with the columns with the same name in the second table . In the natural connection, the user does not need to explicitly specify the columns to be connected. This task is automatically completed by the Oracle system. The natural connection uses **"NATURAL JOIN" keyword.**

Retrieve the records whose salary (sal field) is greater than 2000 in the emp table, and realize the natural connection between the emp table and the dept table.

emp:
insert image description here

dept:
insert image description here

SELECT EMPNO,ENAME,JOB,DNAME
FROM EMP NATURAL JOIN DEPT
WHERE SAL>2000;

insert image description here

Example 4: Self-join

Self-join : A table is joined to itself
Need to alias the table to show the difference
Since all property names are properties of the same name, an alias prefix must be used

View the parent title of each title
insert image description here

SELECT FIRST.DLEVELID,FIRST.DLEVELNAME,FIRST.FATHERLEVEL,
SECOND.DLEVELID,SECOND.DLEVELNAME
FROM DOCTOR_LEVEL FIRST,DOCTOR_LEVEL SECOND
WHERE FIRST.FATHERLEVEL=SECOND.DLEVELID

result:
insert image description here

Example 5: Outer join

The difference between outer join and normal join

1.普通连接操作只输出满足连接条件的元组
2.外连接操作以指定表为连接主体,将主体表中不满足连接条件的元组一并输出
3.左外连接:列出左边关系中所有的元组 
4.右外连接:列出右边关系中所有的元组 

There are usually three types of outer joins:

  • Left outer join: the key isLEFT OUTER JOIN或LEFT JOIN。
  • Right outer join: the key isRIGHT OUTER JOIN 或RIGHT JOIN。
  • Full outer join: the keyword isFULL OUTER JOIN或FULL JOIN。

DOCTOR_INFORMATION
insert image description here

DOCTOR_LEVEL
insert image description here

  • Left outer join : The query result of the left outer join not only contains the data rows that meet the join conditions, but also includes the data rows that do not meet the join conditions in the left table.
SELECT DOCTOR_INFORMATION.*,DOCTOR_LEVEL.*
FROM DOCTOR_INFORMATION
LEFT JOIN DOCTOR_LEVEL
ON (DOCTOR_INFORMATION.DOCTORSAL=DOCTOR_LEVEL.DLEVELSAL);

result:
insert image description here

  • Right outer join : The query result of the right outer join not only contains the data rows that meet the join conditions, but also includes the data rows that do not meet the join conditions in the right table.
SELECT DOCTOR_INFORMATION.*,DOCTOR_LEVEL.*
FROM DOCTOR_INFORMATION
RIGHT JOIN DOCTOR_LEVEL
ON (DOCTOR_INFORMATION.DOCTORSAL=DOCTOR_LEVEL.DLEVELSAL);

result:
insert image description here

  • Full outer join: When performing a full outer join, Oracle will perform a complete left outer join and right outer join query, then merge the query results and eliminate duplicate record rows.
SELECT DOCTOR_INFORMATION.*,DOCTOR_LEVEL.*
FROM DOCTOR_INFORMATION
FULL JOIN DOCTOR_LEVEL
ON (DOCTOR_INFORMATION.DOCTORSAL=DOCTOR_LEVEL.DLEVELSAL);

result:
insert image description here

4. Nested queries

(1) What is a nested query?

A SELECT-FROM-WHERE statement is called a query block,A query that nests one query block within the conditions of another query block's WHERE clause or HAVING phrase is called a nested query

SELECT select_list
FROM tablename
WHERE expr_operator
      (SELECT select_list
        FROM table);

  • The upper query block is called the outer query or parent query, and the lower query block is called the inner query or subquery
  • The SQL language allows multi-level nested queries, that is, a subquery can also nest other subqueries

(2) Classification:

According to the solution method

  • Uncorrelated subquery: The query conditions of the subquery do not depend on the parent query, and are processed layer by layer from the inside out.That is, each sub-query is solved before the upper-level query processing, and the results of the sub-query are used to establish the search conditions of its parent query
  • Correlated subqueries:The query condition of the subquery depends on the parent query. First take the first tuple of the table in the outer query, process the inner query according to its attribute value related to the inner query, if the return value of the WHERE clause is true, take this tuple and put it into the result table, and then Get the next tuple of the outer table. Repeat this process until all the outer tables have been checked.

According to the query results

  • Single row subquery: inner SELECT command returns one record
  • Multi-row subquery: inner SELECT command returns multiple records
  • Multi-column subquery: the inner SELECT command returns multiple data columns

(3) Rules for using subqueries

  • Subqueries are enclosed in parentheses
  • Place the subquery to the right of the comparison operator
  • Do not add an ORDER BY clause to the subquery
  • Use single-row operators (such as =,>,<) for single-row subqueries, and you can also use multi-row operators
  • Use multi-row operators for multi-row subqueries, IN, ANY, ALL are multi-row operators

(4) Mistakes that are easy to make in subqueries

  • Use single-row operators, but the subquery returns multiple rows
  • No records were returned in the inner query

(5) Explain with examples

Example 1: Subquery with IN predicate

SELECT ENAME,DEPTNO,SAL 
FROM EMP 
WHERE SAL IN (
	SELECT MAX(SAL) 
	FROM EMP 
	GROUP BY DEPTNO);

Example 2: Subquery with comparison operators

SELECT ENAME,SAL 
FROM EMP 
WHERE SAL>(
	SELECT SAL 
	FROM EMP 
	WHERE ENAME='JONES');

Example 3: Subquery with ANY(SOME) or ALL predicate

The semantics are:

1.> ANY	大于子查询结果中的某个值       
2.> ALL	大于子查询结果中的所有值
3.< ANY	小于子查询结果中的某个值    
4.< ALL	小于子查询结果中的所有值
5.>= ANY	大于等于子查询结果中的某个值    
6.>= ALL	大于等于子查询结果中的所有值
7.<= ANY	小于等于子查询结果中的某个值    
8.<= ALL	小于等于子查询结果中的所有值
9.= ANY	等于子查询结果中的某个值        
10.=ALL	等于子查询结果中的所有值(通常没有实际意义)
11.!=(或<>)ANY	不等于子查询结果中的某个值
12.!=(或<>)ALL	不等于子查询结果中的任何一个值

Summarize:
insert image description here

Example: Find the names of employees whose wages are lower than any type of 'CLERK' and not 'CLERK'. The
following query results are known:
insert image description here
insert image description here

SELECT ENAME ,DEPTNO, JOB,SAL
FROM EMP
WHERE SAL< ANY (
	SELECT SAL 
	FROM EMP
	WHERE JOB ='CLERK')
AND JOB<>'CLERK';

The result is:
insert image description here

Example 4: Subquery with EXISTS predicate

A subquery with an EXISTS predicate returns no data, only a logical true value or a logical false value "false".

  • If the inner query result is not empty, the outer WHERE clause returns true
  • If the inner query result is empty, the outer WHERE clause returns a false value

For the subquery induced by EXISTS, the target column expression usually uses *, because the subquery with EXISTS only returns true or false values, and the column name is meaningless

NOT EXISTS predicate

  • If the inner query result is not empty, the outer WHERE clause returns a false value
  • If the inner query result is empty, the outer WHERE clause returns true

Query all doctors with professional titles

SELECT DOCTORNAME,DOCTORSEX,DOCTORSAL
FROM DOCTOR_INFORMATION
WHERE EXITS(
	SELECT *
	FROM DOCTOR_LEVEL
	WHERE DOCTOR_INFORMATION.DOCTORSAL=DOCTOR_LEVEL.DLEVELSAL);

result:
insert image description here

5. Set query

(1) What is set query?

Types of set operations

  • And operate UNION
  • Post operation INTERSECT
  • Poor operation MINUS

The number of columns of each query result participating in the set operation must be the same; the data types of the corresponding items must also be the same

(2) Explain with examples

First, the following query results have been obtained:
insert image description here
insert image description here

Example 1: and operate UNION

SELECT *
FROM EMP 
WHERE JOB='MANAGER'
UNION
SELECT * 
FROM EMP
WHERE DEPTNO='30';

insert image description here

Example 2: Intersection operation INTERSECT

SELECT *
FROM EMP 
WHERE JOB='MANAGER'
INTERSECT
SELECT * 
FROM EMP
WHERE DEPTNO='30';

insert image description here

Example 3: Difference operation MINUS

SELECT *
FROM EMP 
WHERE JOB='MANAGER'
MINUS
SELECT * 
FROM EMP
WHERE DEPTNO='30';

insert image description here


Summarize

Please bear with me and correct me if the article is inappropriate.
For readers who want to understand the basic concepts, the following articles can be used for your reference:
Overview of SQL language and data definition of SQL language

Guess you like

Origin blog.csdn.net/weixin_52042488/article/details/127095812