SQL advanced statement select usage


Create a sample table

Insert picture description here

[root@mysql1 ~]# mysql -uroot -p
Enter password: 
.....此处省略
mysql> create database school;
Query OK, 1 row affected (0.00 sec)

mysql> use school;
Database changed

##创建成绩表##
mysql> create table result(id int(3), name varchar(64), Maths int(3),  English int(3));
Query OK, 0 rows affected (0.01 sec)

mysql> insert into result values(001,'zhangsan',90,85),(002,'lisi',90,80),(003,'wangwu',87,85),(004,'zhaoliu',93,80),(005,'xiaoming',80,95),(006,'xiaohong',95,87),(007,'xiaogang',83,89);
Query OK, 7 rows affected (0.00 sec)
Records: 7  Duplicates: 0  Warnings: 0

mysql> select * from result;
+------+----------+-------+---------+
| id   | name     | Maths | English |
+------+----------+-------+---------+
|    1 | zhangsan |    90 |      85 |
|    2 | lisi     |    90 |      80 |
|    3 | wangwu   |    87 |      85 |
|    4 | zhaoliu  |    93 |      80 |
|    5 | xiaoming |    80 |      95 |
|    6 | xiaohong |    95 |      87 |
|    7 | xiaogang |    83 |      89 |
+------+----------+-------+---------+
7 rows in set (0.01 sec)

##创建宿舍表
mysql> create table dormitory(id int(3), room int(3));
Query OK, 0 rows affected (0.01 sec)

mysql> insert into dormitory values(001,501),(002,501),(003,502),(004,502),(005,502),(006,503),(007,503);
Query OK, 7 rows affected (0.00 sec)
Records: 7  Duplicates: 0  Warnings: 0

mysql> select * from dormitory;
+------+------+
| id   | room |
+------+------+
|    1 |  501 |
|    2 |  501 |
|    3 |  502 |
|    4 |  502 |
|    5 |  502 |
|    6 |  503 |
|    7 |  503 |
+------+------+
7 rows in set (0.00 sec)

mysql> 

Keyword ranking

Use the ORDER BY statement to achieve sorting.
Sorting can be based on one or more fields

grammar structure

SELECT colum1,colum2,....FROM table_name ORDER BY colum1,colum2,.... ASC|DESC;

ASC:Ascending order, the default sorting method
DESC: Descending order

Sort by single field

Sort by English score in descending order

select id,name,Maths,English from result order by English desc;

Insert picture description here
Sort in ascending order of math grades

select id,name,Maths,English from result order by Maths;

Insert picture description here
Sort by multiple fields

Sort in ascending order of math scores, same as math scores, sorted in ascending order of English scores

select id,name,Maths,English from result order by Maths,English;

Insert picture description here

Group the results

Use the group by statement to achieve grouping,
usually combined with aggregate functions. The
results can be grouped by one or more fields.

Group those with math scores over 85 and count the same number of math scores

select count(name),Maths from result where Maths>85 group by Maths;

Insert picture description here
Sort the above results in descending order

select count(name),Maths from result where Maths>85 group by Maths order by Maths desc;

Insert picture description here

Limit result entries

Only return the first row or the first few rows of the select query result
Use the limit statement to limit entries

limit syntax structure

select 字段1,字段2 from 表名 limit [offset,] number;

offset: Position offset, starting from 0
number: Return the maximum number of record lines

Only show the default first three rows of the score table

select * from result limit 3;

Insert picture description here

Display three lines after the third line

select * from result limit 2,3;

Insert picture description here

Only display the top three IDs, names, and English scores of the top three English scores

select id,name,English from result order by English desc limit 3;

Insert picture description here

Set alias

Use the as statement to set the alias, the keyword as can be omitted. When
setting the alias, ensure that it does not conflict with the names of other tables or fields in the library

Syntax structure of
alias Field alias: select 字段 as 别名 from 表名;
table alias:select 字段 from 表名 as 别名

Set the alias for the id in the result table as the student number

select id as xuehao from result;

Insert picture description here

Two tables connected query

Both result and dormitory have a common column id, which connects the two tables through the same field

select * from result inner join dormitory on result.id=dormitory.id;

Insert picture description here
Query name and corresponding dormitory

select result.name,dormitory.room from result inner join dormitory on result.id=dormitory.id;

Insert picture description here

Wildcard

Used to replace part of the characters in the string.
Usually used with like, and cooperate with where to complete the query.
Commonly used wildcards
%represent zero, one or more, that is, any character
_represents a single character

Query the name starting with x in the result table

select * from result where name like 'x%';

Insert picture description here
Query the name of zhangsa (any character) in the result table

select * from result where name like 'zhangsa_';

Insert picture description here
Query the name of xiao (any four characters) in the result table

select * from result where name like 'xiao____';

Insert picture description here
Match any character at the beginning, match an h, and match any character at the end

mysql> select * from result where name like '_h%';

Insert picture description here

Subquery

Also known as inner query or nested query
. It is executed before the main query, and its result will be used as the condition of the outer main query. Subqueries
can be used in addition, deletion and modification of the query.
Multi-level nested
in statement is used to determine whether a value is In the given result set

select id,name from result id where id in(1,2);

Insert picture description here

select * from result where id in(select id from result where Maths>90);

Insert picture description here
not equal to

select * from result where id!=(select id from result where name='zhangsan');

Insert picture description here

select * from result where id<>(select id from result where name='zhangsan');

Insert picture description here
Nested

select * from result where id in (select result.id from (select id from result where Maths>90)result);

Insert picture description here

update result set Maths=Maths-5 where id in (select result.id from (select id from result where Maths>60)result);

Insert picture description here
exists

select * from result where exists (select * from dormitory where room like '50_');

The following statement is executed successfully, and the previous statement is executed

Insert picture description here

NULL value

null: vacuum (nothing)
1, indicates missing value
2, is different from the number 0 or blanks (spaces)
3, use is null or is not null to judge
4, null value and empty value ('') Differences The
length of a null value is 0 and does not occupy space; the length of a null value is null, and the space occupied
is null cannot determine the null value. When a
null value uses "=" or "<>" to process the
count() calculation, null will be ignored and empty Value will be added to the calculation

Create a table

create table a(id int(3), name varchar(64), score int(3));
insert into a value(1,'zhangsan',95),(2,'lisi',NULL),(3,NULL,NULL);

Insert picture description here
Query for null values

select * from a where name is null;

Insert picture description here

Query for non-empty values

select * from a where score is not null;

Insert picture description here

Regular expression

According to the specified matching mode, match the special characters that meet the requirements in the record.
Use the regexp keyword to specify the matching mode

Common matching patterns

character Description
^ Match the beginning of the text
$ Match the end character of the text
. Matches any single character
* Match the preceding character zero or more times
+ Match the preceding character one or more times
String Match contains the specified string
p1lp2 Match p1 or p2
[…] Match any character in the character set
[^…] Match any character not in brackets
{n} Match the preceding string n times
{n,m} Match the preceding string at least n times, as many as m times

1. Records beginning with a specific string

select * from result where name regexp '^z';

Insert picture description here
2. Records ending with a specific string

select * from result where name regexp 'g$';

Insert picture description here
3. Records containing the specified string

select * from result where name regexp 'xiao';

Insert picture description here

4. Replace any character in the string with "."

select * from result where name regexp 'zhang...';

Insert picture description here

5. Match records containing or relationship

select * from result where name regexp 'san|si';

Insert picture description here
6. "*" matches any number of previous characters

select * from result where name regexp 'zh*';

Insert picture description here

7. "+" matches the preceding character at least once

select * from result where name regexp 'z+';

Insert picture description here
8. Match any one of the specified character set

select * from result where name regexp '^[a-z]';

Insert picture description here

Operator


There are four types of MySQL operators used to perform operations on field values ​​in records , namely: arithmetic operators, comparison operators, logical operators, and bitwise operators

Arithmetic Operator

Operator description
+ addition
- Subtraction
* multiplication
/ division
% Take the remainder

select command to implement the most basic addition, subtraction, multiplication and division operations

select 1+3,4-3,2*3,6/2,5%2;

Insert picture description here
PS:
Integer division, the result is floating point.
In the division operation and the remainder operation, the divisor cannot be 0, if the divisor is 0, the returned result is NULL

Addition, subtraction, multiplication and division mixed operations

Insert picture description here

Comparison operator

Operator description Operator description
= equal is not null Determine whether a value is not NULL
> more than the between
and
Between the two
< Less than in In the collection
>= greater or equal to like Universal character matching
<= Less than or equal to greatest Return the maximum value for two or more parameters
!= or <> not equal to least Two or more parameters return the minimum value
is null Determine whether a value is NULL regexp Regular expression

1. Equal to operator

select 1=1,1=2,1='1','a'='a','a'='b','a'=null;

Insert picture description here
Comparison rules:

If both are integers, the comparison is performed according to the integer value.
If an integer is a string, the string is automatically converted to a number and then compared.
If both are strings, they are compared according to the strings.
If at least one of the two values ​​is NULL, the result of the comparison is NULL.

2. Not equal to operator
There are two ways of writing, <> or !=, which is used to compare numbers, strings and expressions that are not equal.
If they are not equal, return 1 and if they are equal, return 0.
PS: The inequality operator cannot be used to judge NULL.

select 'ab'!='ab', 'ab'<>'abc',1!=2,1<>2,1<>null;

Insert picture description here
3. Greater than, greater than or equal, less than, less than or equal to operators

(Cannot be used to judge NULL)

select 1>2 ,2>1, 1>=2, 2>=1, 1>=null;

Insert picture description here
4. IS NULL, IS NOT NULL
IS NULL Judge whether a value is NULL, return 1 if it is NULL, otherwise return 0.
IS NOT NULL Determines whether a value is not NULL, if it is not NULL, it returns 1, otherwise it returns 0.

select 'a' is null, 'a' is not null, null is null , null is not null;

Insert picture description here
5.between and

select 3 between 1 and 3, 4 between 1 and 3, 'c' between 'a' and 'c', 'd' between 'a' and 'c';

Insert picture description here
6.least、greatest

LEAST: When there are two or more parameters, the minimum value is returned. If one of the values ​​is NULL, the return result is NULL.
GREATEST: When there are two or more parameters, the maximum value is returned. If one of the values ​​is NULL, the return result is NULL.

select least(1,2,3),greatest(1,2,3);

Insert picture description here

select least('a','b','c'),greatest('a','b','c');

Insert picture description here
7.in, not in
IN Determine whether a value is in the corresponding list, if it is, it returns 1, otherwise it returns 0.
NOT IN judges whether a value is not in the corresponding list, if it is not, it returns 1, otherwise it returns 0.

select 1 in (1,2,3), 'a' in ('a','b','c'), 'a' in (1,2,3);

Insert picture description here
8. Like and not like
LIKE are used to match strings. If the match is successful, it returns 1, otherwise it returns 0; NOT LIKE is the opposite of LIKE.
LIKE supports two wildcards:'%' is used to match any number of characters, and'_' can only match one character.

select 'zhangsan' like 'zhang%', 'zhangsan' like 'zhangsa_' ,'zhangsan' not like '_hangsan';

Insert picture description here

Logical Operators

Operator description
NOT or! Logical negation
AND 或 && Logical and
OR或 || Logical OR
XOR Logical exclusive OR

1. Logic negation Logic
negation negates the logical test that follows it, turning true to false and false to true.
If the operand following NOT is 0, the resulting value is 1; if the operand is non-zero, the resulting value is 0; if the operand is NULL, the resulting value is NULL.
Note: non-zero values ​​are all 1

select not 2, ! 0, not(1-1), ! null;

Insert picture description here

2. Logical AND
If all values ​​are true, return 1; otherwise, return 0.

select 1 and 2, 2 && 2 , 1 and null, 1 and 0, 0 && null;

Insert picture description here

3.逻辑或(最好用or)
逻辑或表示包含的操作数,任意一个为非零值并且不是 NULL 值时,返回 1,否则返回0。

select 1 or 1, 1 or 0, 1 or null, 0 or null, 0 or 0;

Insert picture description here

4.逻辑异或
两个非 NULL 值的操作数,如果两者都是 0 或者都是非 0,则返回 0;如果一个为 0, 另一个为非 0,则返回结果为 1;
当任意一个值为 NULL 时,返回值为 NULL。

select 0 xor 1, 1 xor 1, 0 xor 0, 0 xor null;

Insert picture description here

5.总结
and运算,只要碰到0就是0,(非0和null是null)
or运算,只要碰到非0值就是1,(0和null是null)
异或运算,只要碰到null都是null

位运算符

位运算符实际上是对二进制数进行计算的运算符。

运算符 描述
& 按位与
| 按位或
~ 按位取反
^ 按位异或
<< 按位左移
>> 按位右移
select 10&15 , 10|15, 10^15, 5&~1;

Insert picture description here

按位与运算

十进制   10 & 15    #10和15按位与运算
二进制 1010 & 1111    #转换为2进制

1010
1111
—————  #对应的二进制位都是 1 的,它们的运算结果为 1,否则为 0
1010

10          #1010转换为十进制

按位或运算

十进制   10 & 15    #10和15按位与运算
二进制 1010 & 1111    #转换为2进制

1010
1111
—————  #对应的二进制只要有一个是1,结果就为1
1111

15          #1111转换为十进制

按位异或运算

十进制   10 & 15    #10和15按位与运算
二进制 1010 & 1111    #转换为2进制

1010
1111
—————  #对应的二进制位不相同时,运算结果 1,否则为 0
0101

5          #0101转换为十进制

按位取反运算

5&~1

5 转 二进制 为 101
1 转 二进制 为 001
1 按位取反  为 110

101
110
————  #按位与运算
100

4  # 100转十进制为4
select 1<<2, 31>>3, 24>>3;

Insert picture description here

按位左移运算

1 转 十进制 为 1
左移2位后 为 100 
100 转为十进制 为 4

31 转 十进制 为 11111
右移3位后 为 11    多余的位数直接删除
11 转为十进制 为 3

24 转 十进制 为 11000
右移3位后 为 11   多余的位数直接删除
11 转为十进制 为 3

常用的运算符优先级

优先级 运算符
1
2 ~
3 ^
4 */(DIV),%(MOD)
5 +,-
6 >>,<<
7 &
8 |
9 =,<=>,>=,>,<=,<,<>,!=,IS,LIKE,REGEXP,IN
10 BETWEEN,CASE,WHEN,THEN,ELSE
11 NOT
12 &&,AND
13 ||,OR,XOR
14 :=

连接查询

创建表

create table info(id int(3), age int(3), name varchar(64), class varchar(64));
insert into info values(1,18,'zhangsan','7(1)'),(2,19,'lisi','7(1)'),(3,19,'wangwu','7(1)');

Insert picture description here

通常都是将来自两个或多个表的行结合起来,基于这些表之间的共同字段,进行数据的拼接。
要先确定一个主表作为结果集,然后将其他表的行有选择性的连接到选定的主表结果集上。

使用较多的连接查询包括:内连接、左连接和右连接

1.内连接

Use the keyword inner join in the from clause to join multiple tables, and use the on clause to set the join conditions.
Inner join is the system default table join, so the INNER keyword can be omitted after the FROM clause, and only the keyword JOIN can be used. When there are multiple tables at the same time, you can also use INNER JOIN continuously to realize the inner join of multiple tables, but for better performance, it is recommended that you do not exceed three tables.

2. Outer join
Left join, the main table is on the left, the contents of the main table will all be displayed, and the ones that are not matched in the secondary table will be displayed as NULL

select dormitory.room,info.class from dormitory left join info on dormitory.id=info.id;

Insert picture description here
Right connection, the main table is on the right, all the contents of the main table will be displayed, and the ones that are not matched in the secondary table will be displayed as NULL

select dormitory.room,info.class from dormitory right join info on dormitory.id=info.id;

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_50345511/article/details/111710572