131 MySQL single-table queries (important)

First, the sequence of syntax and keywords perform single-table queries

1.1 single-table query syntax

SELECT DISTINCT 字段1,字段2... FROM 表名
                              WHERE 条件
                              GROUP BY field
                              HAVING 筛选
                              ORDER BY field
                              LIMIT 限制条数

1.2 key priority of execution

  1. from: find the table
  2. where: where the specified constraint holds, to the file / table records a taken
  3. group by: one records the extracted grouping group by, if there is no group by, the whole as a group
  4. having: a result of the grouping is filtered HAVING
  5. distinct: de-duplication
  6. order by: Sort results by conditions: order by
  7. limit: limit the number of results displayed

Note: a query, you can have a variety of screening conditions, the conditions of the order must be carried out stepwise selection in the order above, distinct little special (writing position), the kind of conditions can be deleted, but not out of order

Second, a simple query

"""
增:
insert [into] 
    [数据库名.]表名[(字段1[, ..., 字段n])] 
values 
    (数据1[, ..., 数据n])[, ..., (数据1[, ..., 数据n])];

删:
delete from [数据库名.]表名 [条件];

改:
updata [数据库名.]表名 set 字段1=值1[, ..., 字段n=值n] [条件];

查:
select [distinct] 字段1 [[as] 别名1],...,字段n [[as] 别名n] from [数据库名.]表名 [条件];
"""

# 条件:from、where、group by、having、distinct、order by、limit => 层层筛选后的结果

2.1 Data Preparation

CREATE TABLE `emp`  ( 
  `id` int(0) NOT NULL AUTO_INCREMENT,
  `name` varchar(10) NOT NULL,
  `gender` enum('男','女','未知') NULL DEFAULT '未知',
  `age` int(0) NULL DEFAULT 0,
  `salary` float NULL DEFAULT 0,
  `area` varchar(20) NULL DEFAULT '中国',
  `port` varchar(20) DEFAULT '未知',
  `dep` varchar(20),
  PRIMARY KEY (`id`)
);

INSERT INTO `emp` VALUES 
    (1, 'yangsir', '男', 42, 10.5, '上海', '浦东', '教职部'),
    (2, 'engo', '男', 38, 9.4, '山东', '济南', '教学部'),
    (3, 'jerry', '女', 30, 3.0, '江苏', '张家港', '教学部'),
    (4, 'tank', '女', 28, 2.4, '广州', '广东', '教学部'),
    (5, 'jiboy', '男', 28, 2.4, '江苏', '苏州', '教学部'),
    (6, 'zero', '男', 18, 8.8, '中国', '黄浦', '咨询部'),
    (7, 'owen', '男', 18, 8.8, '安徽', '宣城', '教学部'),
    (8, 'jason', '男', 28, 9.8, '安徽', '巢湖', '教学部'),
    (9, 'ying', '女', 36, 1.2, '安徽', '芜湖', '咨询部'),
    (10, 'kevin', '男', 36, 5.8, '山东', '济南', '教学部'),
    (11, 'monkey', '女', 28, 1.2, '山东', '青岛', '教职部'),
    (12, 'san', '男', 30, 9.0, '上海', '浦东', '咨询部'),
    (13, 'san1', '男', 30, 6.0, '上海', '浦东', '咨询部'),
    (14, 'san2', '男', 30, 6.0, '上海', '浦西', '教学部'),
    (15, 'ruakei', '女', 67, 2.501, '上海', '陆家嘴', '教学部');

Third, the de-emphasis (distinct)

mysql>: 
create table t1(
    id int,
    x int,
    y int
);
mysql>: insert into t1 values(1, 1, 1), (2, 1, 2), (3, 2, 2), (4, 2, 2);

# 去重
mysql>: select distinct * from t1;  # 全部数据
mysql>: select distinct x, y from t1;  # 结果 1,1  1,2  2,2
mysql>: select distinct y from t1;  # 结果 1  2

Summary: distinct participate in all fields of inquiry, the overall de-emphasis (the value of all the fields of the same investigation, was considered to be duplicate data)

Fourth, the commonly used functions

  • Stitching: concat () | concat_ws () , except that the stitching concat_ws character into a first position, put the field back stitching.
  • Case: Upper () | Lower ()
  • Floating-point operation: ceil () rounded up | Floor () rounded down | round () rounding
  • Integer: direct operation
  • Alias: As long as the alias for the field queries can be used as a keyword, it can be omitted
mysql>: select name,area,port from emp;
# 拼接:concat() | concat_ws()
mysql>: select name as 姓名, concat(area,'-',port) 地址 from emp;  # 对查询的结果取别名显示
mysql>: select name as 姓名, concat_ws("-",area,port,dep) 信息 from emp;

# 大小写
mysql>: select upper(name) 姓名大写, lower(name) 姓名小写 from emp;

# 浮点类型操作
mysql>: select id,salary,ceil(salary)上薪资,floor(salary)下薪资,round(salary)舍入薪资 from emp;

# 整数运算
mysql>: select name 姓名, age 旧年龄, age+1 新年龄 from emp;

V. constraints (where)

Judgment Rule:

  1. Compare Match: >| <| >=| <=| =|!=
  2. Interval match: the BETWEEN start and end | in (custom containers)
  3. Logic Match: and| or|not
  4. Fuzzy Match: like'n-%'
    • Wildcards can be a% or _,
      • % Represents any number of characters
      • _ Represents one character
  5. Regular match: regexp regular grammar
# 多条件协调操作导入:where 奇数 [group by 部门 having 平均薪资] order by [平均]薪资 limit 1

# 比较匹配
mysql>: select * from emp where salary>5;   # 查询salary>5的全部记录
mysql>: select * from emp where id%2=0;     # 查询id为偶数的全部记录
mysql>: select * from emp where id%2=1;     # 查询id为奇数的全部记录

# 区间匹配
mysql>: select * from emp where salary between 6 and 9; # 查询 salary 在 6-9 范围内的记录

# 模糊匹配
mysql>: select * from emp where name like "%w%";    # 匹配name字段 中包含w的记录
mysql>: select * from emp where name like "_w%";    # 匹配name字段 中包含一个任意字符w的记录
mysql>: select * from emp where name like "__e%";   # 匹配name字段 中包含两个任意字符w的记录

# sql只支持部分正则语法
mysql>: select * from emp where name regexp '.*[0-9]';  # 支持[]语法

Six, aggregate functions

  • max (): maximum value
  • min (): minimum value
  • avg (): average
  • sum (): sum
  • count (): count
  • group_concat (): the group field splicing

He emphasized: polymerizing a polymerizable function group content is, if no packets, the default set.

# 求全部记录的个数
mysql>: select count(*) from emp;

# 求字段salary的最大数据
mysql>: select max(salary) from emp;

# 求字段salary的最小数据
mysql>: select min(salary) from emp;

# 求字段salary的平均数据
mysql>: select avg(salary) from emp;

# 对 字段salary的数据 求和
mysql>: select sum(salary) from emp;

Seven, grouping and filtering (group by | having)

7.1 Packet query (group by)

The unitary pieces of data in this way is called a polymerization

Each department who has the highest salary, the minimum salary, average salary are called polymerization results - aggregate function operating results

NOTE: participation field of the packet, is attributed to polymerization results

After grouping, the data in Table consideration is not a single record, because each packet contains a plurality of records, reference packet fields, unitary many records in each packet

# 修改my.ini配置重启mysql服务
sql_mode=ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

# 在sql_mode没有 ONLY_FULL_GROUP_BY 限制下,可以执行,但结果没有意义
# 有 ONLY_FULL_GROUP_BY 限制,报错
mysql>: select * from emp group by dep;

# eg: 按部门分组,查询每个部门都有哪些人、最高的薪资、最低的薪资、平均薪资、组里一共有多少人
mysql>: 
select 
    dep 部门,
    group_concat(name) 成员, 
    max(salary) 最高薪资,
    min(salary) 最低薪资, 
    avg(salary) 平均薪资, 
    sum(salary) 全部工资, 
    count(salary) 部门人数 
from emp group by dep;

# eg: 按部门分组,查询每个组年龄最大的记录
mysql>: select dep 部门, max(age) 最高年龄 from emp group by dep;

7.2 where the difference of having

  • In the absence of a packet, the same result where the having
  • Key: having polymerization can filter the results
# 没有分组进行筛选,没有区别
mysql>: select * from emp where salary > 5;
mysql>: select * from emp having salary > 5;

After having 7.3 Packet

  • Key: having polymerization can filter the results
# eg: 按部门分组,查询每个部门中最低薪资小于5的记录
mysql>: 
select
    dep 部门,
    group_concat(name) 成员,
    max(salary) 最高薪资,
    min(salary) 最低薪资,
    avg(salary) 平均薪资,
    count(salary) 部门人数
from emp group by dep having min(salary) < 5;

# having可以对 聚合结果 再进行筛选,where不可以

Eight, sorting (order by)

  • Ascending order (from low to high): asc(default ascending)
  • Descending (highest to lowest):desc

8.1 Collation

order by 排序字段 [asc|desc], 排序字段1 [asc|desc], ..., 排序字段n [asc|desc]

8.2 ungrouped

mysql>: select * from emp

# 按年龄升序(从低到高)
mysql>: select * from emp order by age asc;
# 按年龄降序(从高到低)
mysql>: select * from emp order by age desc;

8.3 Status Packet

# 按部门分组后, 排序部门人数为降序(从高到低)
mysql>: 
select 
    dep 部门,
    group_concat(name) 成员,
    max(salary) 最高薪资,
    min(salary) 最低薪资,
    avg(salary) 平均薪资,
    sum(salary) 总薪资,
    count(salary) 部门人数
from emp group by dep order by 部门人数 desc;

# 按部门分组后, 排序部门人数为升序(从低到高)
mysql>: 
select 
    dep 部门,
    group_concat(name) 成员,
    max(salary) 最高薪资,
    min(salary) 最低薪资,
    avg(salary) 平均薪资,
    sum(salary) 总薪资,
    count(salary) 部门人数
from emp group by dep order by 部门人数;    # 默认升序

Nine, restrictions limit

Syntax: limit the number of | limit offset, the number of bars

# 语法:limit 条数  |  limit 偏移量,条数
mysql>: select name, salary from emp where salary<8 order by salary desc limit 1;

mysql>: select * from emp limit 5,3;  # 先偏移5条满足条件的记录,再查询3条

Ten, even table query

  • Connection: there will be multiple tables linked by the link (the line connected, not necessarily a foreign key) field, a connection, a large table parameter
  • Even table query: query on the basis of a large table, it is called even-table query
  • The table and the table in establishing a connection there are four: internal connections, connect the left and right connections, fully connected

data preparation

mysql>: 
create table dep(
    id int primary key auto_increment,
    name varchar(16),
    work varchar(16)
);
create table emp(
    id int primary key auto_increment,
    name varchar(16),
    salary float,
    dep_id int
);
insert into dep values(1, '市场部', '销售'), (2, '教学部', '授课'), (3, '管理部', '开车');
insert into emp(name, salary, dep_id) values('egon', 3.0, 2),('yanghuhu', 2.0, 2),('sanjiang', 10.0, 1),('owen', 88888.0, 2),('liujie', 8.0, 1),('yingjie', 1.2, 0);

Cartesian Product

# 笛卡尔积: 集合 X{a, b} * Y{o, p, q} => Z{{a, o}, {a, p}, {a, q}, {b, o}, {b, p}, {b, q}}

mysql>: select * from emp, dep;

# 总结:是两张表 记录的所有排列组合,数据没有利用价值

En

  • Keywords:inner join on(inner可以省略)
  • grammar:from A表 inner join B表 on A表.关联字段=B表.关联字段
mysql>: 
select emp.id,emp.name,salary,dep.name,work 
from dep inner join emp on dep.id=emp.dep_id;   # 内连接的inner可以省略

Summary: retaining only two tables have associated data

Left connection

  • Keywords:left join on

  • grammar:from A表 left join B表 on A表.关联字段=B表.关联字段

mysql>: 
select 
    emp.id,emp.name,salary,dep.name,work 
from emp left join dep on emp.dep_id = dep.id 
order by emp.id;

Summary: to retain all the data left table, right table there is a direct link corresponding data table shows, there is no correspondence between filling empty

The right connection

  • Keywords:right join on
  • grammar: from A表 left join B表 on A表.关联字段=B表.关联字段
mysql>: 
select 
    emp.id,emp.name,salary,dep.name,work 
from emp right join dep on emp.dep_id = dep.id 
order by emp.id;

Summary: the right to retain all the data tables, the left table has directly connected to the corresponding data table shows, there is no correspondence between filling empty

Can be transformed into each other left and right connecting

mysql>: 
select 
    emp.id,emp.name,salary,dep.name,work 
from emp right join dep on emp.dep_id = dep.id 
order by emp.id;

mysql>: 
select 
    emp.id,emp.name,salary,dep.name,work 
from dep left join emp on emp.dep_id = dep.id 
order by emp.id;

Summary: replace what position around the table, replace the corresponding left and right connection key, same result

Fully connected

The left and right connections to achieve full connection that is connected by keyword

Keywords:union

mysql>: 
select 
    emp.id,emp.name,salary,dep.name,work 
from emp left join dep on emp.dep_id = dep.id 

union

select 
    emp.id,emp.name,salary,dep.name,work 
from emp right join dep on emp.dep_id = dep.id 
order by id;

Summary: Left table Right table data is retained, there is another correspondence between the normal display, do not correspond to each other are empty fill each other

One consistent with many cases

create table author(
    id int,
    name varchar(64),
    detail_id int
);
create table author_detail(
    id int,
    phone varchar(11)
);
insert into author values(1, 'Bob', 1), (2, 'Tom', 2), (3, 'ruakei', 2);
insert into author_detail values(1, '13344556677'), (2, '14466779988'), (3, '12344332255');

select author.id,name,phone from author join author_detail on author.detail_id = author_detail.id order by author.id;

select author.id,name,phone from author left join author_detail on author.detail_id = author_detail.id
union
select author.id,name,phone from author right join author_detail on author.detail_id = author_detail.id
order by id;

Many to many

create table author(
    id int,
    name varchar(64),
    detail_id int
);
insert into author values(1, 'Bob', 1), (2, 'Tom', 2), (3, 'ruakei', 0);

create table book(
    id int,
    name varchar(64),
    price decimal(5,2)
);
insert into book values(1, 'python', 3.66), (2, 'Linux', 2.66), (3, 'Go', 4.66);

create table author_book(
    id int,
    author_id int,
    book_id int
);
# 数据:author-book:1-1,2  2-2,3  3-1,3
insert into author_book values(1,1,1),(2,1,2),(3,2,2),(4,2,3),(5,3,1),(6,3,3);

# 多对多
select book.name, book.price, author.name from book 
join author_book on book.id = author_book.book_id
join author on author_book.author_id = author.id;

# 多对多对1
select book.name, book.price, author.name, author_detail.phone from book 
join author_book on book.id = author_book.book_id
join author on author_book.author_id = author.id
left join author_detail on author.detail_id = author_detail.id;

Guess you like

Origin www.cnblogs.com/XuChengNotes/p/11588528.html