[Database] MySQL Concept Knowledge Grammar-Basic (DQL), really detailed, you will know it in one article

General Grammar and Classification

● DDL: Data Definition Language, used to define database objects (databases, tables, fields)
● DML: Data Manipulation Language, used to add, delete, and modify data in database tables
● DQL: Data Query Language, used to query tables in databases ● DCL
: Data Control Language, used to create database users and control database control authority

DQL (Data Query Language)

grammar:

SELECT
	字段列表
FROM
	表名字段
WHERE
	条件列表
GROUP BY
	分组字段列表
HAVING
	分组后的条件列表
ORDER BY
	排序字段列表
LIMIT
	分页参数

basic query

Query multiple fields :
SELECT 字段1, 字段2, 字段3, ... FROM 表名;
SELECT * FROM 表名;

Set an alias :
SELECT 字段1 [ AS 别名1 ], 字段2 [ AS 别名2 ], 字段3 [ AS 别名3 ], ... FROM 表名;
SELECT 字段1 [ 别名1 ], 字段2 [ 别名2 ], 字段3 [ 别名3 ], ... FROM 表名;

Remove duplicate records :
SELECT DISTINCT 字段列表 FROM 表名;

Escaping :
SELECT * FROM 表名 WHERE name LIKE '/_张三' ESCAPE '/'
_ after / is not used as a wildcard

conditional query

grammar:
SELECT 字段列表 FROM 表名 WHERE 条件列表;

Condition:
comparison operator function

>						大于
>=						大于等于
<						小于
<=						小于等于
=						等于
<>!=				不等于
BETWEEN ... AND ...		在某个范围内(含最小、最大值)
IN(...)in之后的列表中的值,多选一
LIKE 					占位符	模糊匹配(_匹配单个字符,%匹配任意个字符)
IS NULLNULL
逻辑运算符				功能
AND&&				并且(多个条件同时成立)
OR||				或者(多个条件任意一个成立)
NOT!				非,不是

example:

-- 年龄等于30
select * from employee where age = 30;

-- 年龄小于30
select * from employee where age < 30;

-- 小于等于
select * from employee where age <= 30;

-- 没有身份证
select * from employee where idcard is null or idcard = '';

-- 有身份证
select * from employee where idcard;
select * from employee where idcard is not null;

-- 不等于
select * from employee where age != 30;

-- 年龄在20到30之间
select * from employee where age between 20 and 30;
select * from employee where age >= 20 and age <= 30;

-- 下面语句不报错,但查不到任何信息
select * from employee where age between 30 and 20;

-- 性别为女且年龄小于30
select * from employee where age < 30 and gender = '女';

-- 年龄等于25或30或35
select * from employee where age = 25 or age = 30 or age = 35;
select * from employee where age in (25, 30, 35);

-- 姓名为两个字
select * from employee where name like '__';

-- 身份证最后为X
select * from employee where idcard like '%X';

aggregate query (aggregate function)

Common aggregate functions:

  • function function
  • count statistics
  • max maximum value
  • min minimum value
  • avg average value
  • sum

Syntax:
SELECT 聚合函数(字段列表) FROM 表名;
Example:
SELECT count(id) from employee where workaddress = "广东省";

Group query

grammar:
SELECT 字段列表 FROM 表名 [ WHERE 条件 ] GROUP BY 分组字段名 [ HAVING 分组后的过滤条件 ];

The difference between where and having:

● Execution timing is different: where is to filter before grouping, and does not participate in grouping if the where condition is not met; having is to filter the results after grouping.
● The judgment conditions are different: where cannot judge the aggregate function, but having can.

example:

  • According to gender grouping, count the number of men and women (only the number of groups is displayed, not which is male and which is female)
    select count(*) from employee group by gender;

  • According to gender grouping, count the number of men and women
    select gender, count(*) from employee group by gender;

  • According to gender grouping, count the average age of men and women
    select gender, avg(age) from employee group by gender;

  • Age is less than 45, and group by workaddress
    select workaddress, count(*) from employee where age < 45 group by workaddress;

  • The age is less than 45, and group by work address to obtain the work address with the number of employees greater than or equal to 3
    select workaddress, count(*) address_count from employee where age < 45 group by workaddress having address_count >= 3;

Precautions

● Execution sequence: where > aggregation function > having
● After grouping, the fields to be queried are generally aggregation functions and grouping fields, and it is meaningless to query other fields

Sort query

Syntax:
SELECT field list FROM table name ORDER BY field 1 sorting method 1, field 2 sorting method 2;

sort by:

● ASC: ascending order (default)
● DESC: descending order

example:

  • Sort by age in ascending order
    SELECT * FROM employee ORDER BY age ASC;
    SELECT * FROM employee ORDER BY age;

  • Sort by two fields, sort by age in ascending order and entry time in descending order
    SELECT * FROM employee ORDER BY age ASC, entrydate DESC;

Precautions

If it is multi-field sorting, when the first field has the same value, it will be sorted according to the second field

Paging query

Syntax:
SELECT field list FROM table name LIMIT start index, number of query records;

example:

  • Query the data on the first page and display 10 items
    SELECT * FROM employee LIMIT 0, 10;

  • Query the second page
    SELECT * FROM employee LIMIT 10, 10;

Precautions

● The starting index starts from 0, the starting index = (query page number - 1) * the number of records displayed on each page
● Pagination query is a database dialect, different databases have different implementations, MySQL is LIMIT
● If the query is the first page of data , the starting index can be omitted, directly abbreviated as LIMIT 10

Combined query (Cartesian product, all combined results will be displayed):
select * from employee, dept;

Cartesian product: all combinations of two collections A and B (in multi-table queries, invalid Cartesian products need to be eliminated)

Eliminate invalid Cartesian products:
select * from employee, dept where employee.dept = dept.id;

inner join query

The inner join query is the intersection of two tables

Implicit inner join:
SELECT 字段列表 FROM 表1, 表2 WHERE 条件 ...;

Explicit inner join:
SELECT 字段列表 FROM 表1 [ INNER ] JOIN 表2 ON 连接条件 ...;

Explicit performance is higher than implicit

example:

-- 查询员工姓名,及关联的部门的名称
-- 隐式
select e.name, d.name from employee as e, dept as d where e.dept = d.id;
-- 显式
select e.name, d.name from employee as e inner join dept as d on e.dept = d.id;

Outer join query

Left outer join:

-- 查询左表所有数据,以及两张表交集部分数据
SELECT 字段列表 FROM1 LEFT [ OUTER ] JOIN2 ON 条件 ...;
-- 相当于查询表1的所有数据,包含表1和表2交集部分数据

Right outer join:

-- 查询右表所有数据,以及两张表交集部分数据
SELECT 字段列表 FROM1 RIGHT [ OUTER ] JOIN2 ON 条件 ...;

example:

-- 左
select e.*, d.name from employee as e left outer join dept as d on e.dept = d.id;
select d.name, e.* from dept d left outer join emp e on e.dept = d.id;  -- 这条语句与下面的语句效果一样
-- 右
select d.name, e.* from employee as e right outer join dept as d on e.dept = d.id;

Left join can query the employee without dept, and right join can query the dept without employee

self join query

The connection query between the current table and itself, the self-join must use the table alias

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

Self-join query, which can be an inner join query or an outer join query

example:

-- 查询员工及其所属领导的名字
select a.name, b.name from employee a, employee b where a.manager = b.id;
-- 没有领导的也查询出来
select a.name, b.name from employee a left join employee b on a.manager = b.id;

joint query

Combine the results of multiple queries to form a new query set (union, union all)

grammar:

SELECT 字段列表 FROM 表A ...
UNION [ALL]
SELECT 字段列表 FROM 表B ...

Precautions

● UNION ALL will have duplicate results, UNION will not.
● The combined query is more efficient than using or and will not invalidate the index

subquery

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

SELECT * FROM t1 WHERE column1 = ( SELECT column1 FROM t2);

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

According to the subquery results can be 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 can be divided into:

  • after WHERE
  • after FROM
  • after SELECT

scalar subqueries

The result returned by the subquery is a single value ( number, string, date, etc.).
Commonly used operators:- < > > >= < <=

example:

-- 查询销售部所有员工
select id from dept where name = '销售部';
-- 根据销售部部门ID,查询员工信息
select * from employee where dept = 4;
-- 合并(子查询)
select * from employee where dept = (select id from dept where name = '销售部');

-- 查询xxx入职之后的员工信息
select * from employee where entrydate > (select entrydate from employee where name = 'xxx');

column query

The returned result is one column (can be multiple rows).

Commonly used operators:

操作符	描述
IN	在指定的集合范围内,多选一
NOT IN	不在指定的集合范围内
ANY	子查询返回列表中,有任意一个满足即可
SOMEANY等同,使用SOME的地方都可以使用ANY
ALL	子查询返回列表的所有值都必须满足

example:

-- 查询销售部和市场部的所有员工信息
select * from employee where dept in (select id from dept where name = '销售部' or name = '市场部');
-- 查询比财务部所有人工资都高的员工信息
select * from employee where salary > all(select salary from employee where dept = (select id from dept where name = '财务部'));
-- 查询比研发部任意一人工资高的员工信息
select * from employee where salary > any (select salary from employee where dept = (select id from dept where name = '研发部'));

row subquery

The returned result is one row (can be multiple columns).
Common operators: =, <, >, IN, NOT IN

example:

-- 查询与xxx的薪资及直属领导相同的员工信息
select * from employee where (salary, manager) = (12500, 1);
select * from employee where (salary, manager) = (select salary, manager from employee where name = 'xxx');

table subquery

The returned result is multi-row multi-column
common operator: IN

example:

-- 查询与xxx1,xxx2的职位和薪资相同的员工
select * from employee where (job, salary) in (select job, salary from employee where name = 'xxx1' or name = 'xxx2');

-- 查询入职日期是2006-01-01之后的员工,及其部门信息
select e.*, d.* from (select * from employee where entrydate > '2006-01-01') as e left join dept as d on e.dept = d.id;

Summarize

DQL execution order

FROM -> WHERE -> GROUP BY -> SELECT -> ORDER BY -> LIMIT

Guess you like

Origin blog.csdn.net/u013412066/article/details/129138497