MySQL commonly used statements and functions

mysql database, a complete set of commonly used query statements

The following records commonly used SQL DQL statements; basic query, conditional query, fuzzy query, sort query, aggregate function, de-duplication, paging query, limited output, multi-table query...

基本语法:
增:
添加数据:inset into 表名 (列名1,列名2...values(1,值2...)
添加列:alter table 表名 add 列名 数据类型(长度);
删:delete from 表名
删除列:alter table 表名 drop 列名
 可根据需要加上条件,否则删除全表
改:update 表名 set 字段1=值,字段2=...
可根据需要加上条件,否则更新全表
更新列名:alter table 表名 change 旧列名 新列名 数据类型(长度)
查:select 查询列名(多个列名用,隔开)from 表名

1. Basic query

Syntax: select query column name (used for multiple column names, separated) from table name
*PS: query all columns can be used *instead of all column names, *the time complexity is high, when writing a project to list all the need to query Column
Example:
-Query specified column
-Query student ID, name, age
Query specified column

Two-condition query

understanding
The conditional query is to use the
where statement after the basic query during the query , and use the operator after the where to retain the eligible data
Condition symbol
= Equal
!= <> varies
<less than> greater than <= less than or equal>= greater than or equal
and and/and
-----------the conditions on both sides are satisfied at the same time
or or
------------- One of the conditions on both sides is satisfied
in(set) range is within the range of set collection
between value 1 and value 2
------------ between value 1 and value 2 (including critical value, from small to large)
not in inverted
example:
- Query student records of students aged between 20-40
Insert picture description here
- records check student number is not 1, 2
Insert picture description here

Three fuzzy queries

Fuzzy query needs to be placed after where and use like keyword
: wildcard:
%, can match any number of any characters
_, can match any character

 例·:-- 查询姓名以“张”开头的学生记录
select * from stu where sname like '张%';
-- 查询姓名中包含“三”的学生记录
select * from stu where sname like '%三%'

Four sorting query

Sort the queried results in a certain order
order by field [desc|asc] ==> desc descending order, asc ascending order

例:
-- 不写排序类型,默认是升序
select * from stu order by age
-- 查询所有学生记录,按年龄升序排序,如果年龄相同时,按编号降序排序
select * from stu order by age asc,sid desc

Five aggregate functions

Aggregate function:
       count(column name) counts the number of rows where the specified column is not null.
       max(column name) obtains the maximum value in the specified column. If it is a string,
       min(column name) obtains the minimum
       sum (column name) in character order Specify the sum value of the column, calculate the non-number, the result is 0
       avg (column name) Calculate the average value of the specified column, calculate the non-number, the result is 0

Syntax:
select aggregate function from table name [where…]

-- 查询最高成绩和最低成绩:
select max(score) '最高分',min(score) '最低分' from stu;
-- 统计stu表中成绩大于60的最高成绩和最低成绩:
select max(score) '最高分',min(score) '最低分' from stu where score > 60;

ps:
The column name that appears with the aggregate function must appear after the group by.
On the contrary, if there is a field that does not appear after the groupby, the query result is abnormal!

Six deduplication

The deduplication function distinct (column)
deduplicates the data in the specified column

Syntax:
selectdistinct (column name) from table name [where …]

-- 不重复的年龄
select distinct(age) from stu;
-- 查询年龄不重复的共有多少人
select count(distinct age) from stu;

Seven group query

When you need to query by group, you need to use the group by statement.

Syntax:
select * from stu [where …] group by field [order by…]

Groups with the same field value are grouped.
Note:
1 Generally, the operations after grouping are aggregation operations.
2 Divide into several groups, and the result of the virtual table is a few rows of data.
3 Aggregate functions are to perform separate aggregation operations for each group.

Filter after grouping, you need to use the having clause

The difference between hacing and where:
where is the filtering before grouping, and having is the filtering
after grouping. Aggregate functions cannot be used after where, but aggregate functions can be used for having.
Example:

-- 查询男生多少人,女生多少人
select sex,count(*) '人数' from stu group by sex;
-- 查询每个班级的班级编号和每个班级的成绩和:
select cid,sum(score) from stu group by cid;
-- 查询每个班级的班级编号以及每个班级的人数:
select cid '班级',count(sid) '人数' from stu group by cid;
-- 查询成绩总和大于200的班级编号以及成绩和
select cid,sum(score) from stu group by cid having sum(score) > 200
-- having可以使用前面定义的别名
select cid,sum(score) 'sum' from stu group by cid having sum > 200
-- 查询成绩总和大于200的班级编号以及成绩和并根据成绩总和降序
select cid,sum(score) 'sum' from stu group by cid having sum > 200 order by sum asc;

Eight limit output

You can limit the output of the query results.
You can limit the number of output and where to output.

Syntax:
write limit offset at the end of the sql statement, row_count
limit start subscript, number of rows;
for example: limit 0,2; ==> output from the first line, output 2 lines

Example:

   -- 输出前两条
select * from stu limit 0,2;

-- 从第四条开始,输出三条
select * from stu limit 3,3;

Nine functions

Process function

If(expr1,expr2,expr3)
If expr1 is true, return expr2, otherwise return expr3
– isnull() function, judge whether it is empty
– isnull(field) If it is null, return 1 if it is not null return 0

Example:

-- 查询学生id,姓名,成绩,如果成绩为null,显示缺考
select sid,sname,if(isnull(score)=1,'缺考',score) from stu;

CASE WHEN [expr1] THEN [result1]… ELSE [default] END If expr is true, return result1, otherwise return to default
case
when condition then execute statement
when condition then execute statement

else execute statement
end
execute the condition after the first when , If it is true, execute the statement after then,
if the condition after when is false, execute the condition after the second when
If it is all false, execute the statement after else

Example:

-- 查询学生id,姓名,成绩,以及等级
-- (0-59 不及格,60-69中,70-89良,90-100优 )
select sid,sname,score,
	case 
		when score < 60 then '不及格'
    when score < 70 then '中'
		when score < 90 then '良'
		when isnull(score)=1 then '缺考'
		else '优'
	end as '等级'
from stu

More than ten table queries

** Union query-combined result set **

The query results of the two tables are spliced ​​together vertically . The number, type and order of the fields of the two tables joined by
union / union all
are guaranteed to be the same.
Union will de- duplicate when splicing,
union all will splice all the data of the two tables

E.g:

select sid,sname from stu
union all
select cid,cname from class;

Connect query:

There are three types of relationships between tables: one-to-one, one-to
- many, and many -to -many. One -to- one relationship: you can add related fields to any table. One
-to-many relationship: you can only add related fields at the many end.
Many-to-many relationship: need to create a new table, use a third party to represent the relationship

Join query is to multiply multiple tables and multiple rows of data. It will also produce a Cartesian product

Internal connection:

Inner join syntax:
select * from Table 1 inner join Table 2 on Association conditions
Inner join will only retain data that fully meets the association conditions

Example:

-- 查询学生名称、学生成绩、班级名称、班级地址
select sname,score,cname,caddress from stu inner join class on stu.cid = class.cid

-- 内连接可以简写
select * from stu inner join class on stu.cid = class.cid 
-- 简写成
select * from stu,class where stu.cid = class.cid

Outer join

Outer join: Will retain data that does not meet the conditions.
Left outer join-left outer join on
will retain the data that does not meet the conditions in the left table.
Right outer join-right outer join on
will retain the data that does not meet the conditions in the right table.
General outer Keywords can be omitted

Example:

-- 查询全部学生信息,如果有班级信息,一并查出.
select * from stu s left outer join class c on s.cid = c.cid
-- 查询全部班级信息,如果有学生,将学生信息查出
select * from stu s right outer join class c on s.cid = c.cid

Subquery

A subquery is a nested query.
Generally, a subquery appears after:
from, and after using
where as a table , it is used as a condition

Example:

-- 查询与张三同一个班级的学生。
-- 1查出张三的班级
select cid from stu where sname = '张三'
-- 2查出1班的学生
select * from stu where cid = 1
-- 合并成子查询
select * from stu where cid = (select cid from stu where sname = '张三')
-- 成绩高于3号班级所有人的学生信息
-- 1 找到3班最高分
select max(score) from stu where cid = 3
-- 2 找成绩比96高的学生
select * from stu where score > 96
-- 合并
select * from stu where score > (select max(score) from stu where cid = 3)

Self-connection
Self-connection is to connect itself, one table is used as two tables

s1 is the student table and s2 is the leader table
-the leader of s1 is the student in s2
select s1.sid, s1.sname, s2.sid, s2.sname from stu s1, stu s2 where s1.groupLeaderId = s2.sid and s1.sid = 1008

Example table:
create a student table:

DROP TABLE IF EXISTS `stu`;
CREATE TABLE `stu` (
  `sid` int(11) DEFAULT NULL,
  `sname` varchar(25) DEFAULT NULL,
  `age` int(11) DEFAULT NULL,
  `sex` char(6) DEFAULT NULL,
  `score` int(11) DEFAULT NULL,
  `cid` int(11) DEFAULT NULL,
  `groupLeaderId` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- 添加数据
INSERT INTO `stu` VALUES ('1001', '张三', '20', '男', '72', '1', '1003');
INSERT INTO `stu` VALUES ('1002', '李四', '15', '女', '78', '1', '1003');
INSERT INTO `stu` VALUES ('1003', '王五', '95', '男', '99', '1', '1010');
INSERT INTO `stu` VALUES ('1004', '赵六张', '65', '女', '60', '1', '1007');
INSERT INTO `stu` VALUES ('1005', '周七', '55', '男', '78', '3', '1007');
INSERT INTO `stu` VALUES ('1006', '茅十八', '75', '女', '96', '3', '1007');
INSERT INTO `stu` VALUES ('1007', '张三丰', '40', '男', '85', '3', '1010');
INSERT INTO `stu` VALUES ('1008', '李四方', '45', '女', '90', '2', '1010');
INSERT INTO `stu` VALUES ('1009', '艾三弗森', '45', '', '35', '4', '1008');
INSERT INTO `stu` VALUES ('1010', '三欧文', '35', '女', '49', '2', '1008');


Student table:
Student table
Create a class table:

DROP TABLE IF EXISTS `class`;
CREATE TABLE `class` (
  `cid` int(11) DEFAULT NULL,
  `cname` varchar(255) COLLATE utf8_bin NOT NULL,
  `caddress` varchar(255) COLLATE utf8_bin DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

-- ----------------------------
--  添加数据
-- ----------------------------
INSERT INTO `class` VALUES ('1', 'BigData', '102');
INSERT INTO `class` VALUES ('2', 'HTML', '103');
INSERT INTO `class` VALUES ('3', 'VR', '104');
INSERT INTO `class` VALUES ('4', 'Java', '105');

Class Schedule:
Class Schedule

to sum up:

Writing syntax:
select
selection_list --column to be queried
from
table_name-table name to be queried
where condition-filter row condition
group by grouping_clumns-group the results by column
having condition-filter after grouping
order by sort_column-sort
limit offset, row_count – limit the results

Guess you like

Origin blog.csdn.net/CV_Ming/article/details/112389340