Gerenciamento de banco de dados e alta disponibilidade Capítulo 5 Instruções avançadas de SQL
1.1: Classificar por palavras-chave
SELECT column1,column2,...FROM table_name ORDER BY column1,column2,...
ASC|DESC;
mysql> select id,name,score from accp where score>80 order by score desc;
1.2: Classificar por vários campos
mysql> select id,name,score from accp where score>80 order by score desc,id desc;
//注意每个字段都要写asc(默认)或者desc
1.3: Agrupe os resultados
SELECT column_name,aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name;
1.3.1: GROUP BY agrupando o mesmo tipo em um grupo
mysq> select count(name),level from player where level>=45 group by level;
mysql> select count(name),score,age from kgc where score>=80 group by score;
+-------------+-------+-----+
| count(name) | score | age |
+-------------+-------+-----+
| 1 | 80.00 | 20 |
| 2 | 88.00 | 18 |
| 1 | 90.00 | 28 |
+-------------+-------+-----+
1.3.2: GROUP BY 结合 ORDER BY
mysql> select count(name),score,age from kgc where score>=80 group by score order by count(name) desc;
+-------------+-------+-----+
| count(name) | score | age |
+-------------+-------+-----+
| 2 | 88.00 | 18 |
| 1 | 90.00 | 28 |
| 1 | 80.00 | 20 |
+-------------+-------+-----+
1.4: Limitar entradas de resultados
SELECT column1,column2,....FROM table_name LIMIT[offset,] number;
number 返回记录行的最大数目
[offset,] 位置偏移量,从0开始
[a,b] 索引起始值 b代表包括a-1的行开始往下b行
mysql> select id,name from kgc limit 3; //显示前三条数据 起始位是0代表第一条数据,代表第一行
mysql> select id,name from kgc limit 2,3; 起始位2,代表第三条记录,第 3 条记录开始显示之后的 3条数据。
1.5: Definir alias
SELECT column_name AS alias_name FROM table_name;
SELECT column_name(s)FROM table_name AS alias_name;
*字段的别名
mysql> select count(*) as number from player;
+--------+
| number |
+--------+
|3218 |
+--------+
*表的别名
mysql> select a.name,h.hob_name from accp a inner join Hob h on a.hobby=h.id;
把accp表 as a, Hob表 as h 定义别名,as可以省略
from 表 表的别名
1.6: Use curingas em combinação com semelhantes
mysql> select id,name,score from accp where name like 'ss%';
// like ss开头%任意结尾
mysql> select id,name,score from accp where name like '%s%';
//like s 两边任意字符
mysql> create table bbb as select * from kgc; 复制表
1.7: Subconsultas
*IN语句是用来判断某个值是否在给定的结果集中,判断是否等于集合中的某个值
mysql> select name,hobby from accp where hobby in (select id from Hob where hob_name='云计算');
mysql> select name,hobby from accp where hobby in (select id from Hob);
+----------+-------+
| name | hobby |
+----------+-------+
| wangwu | 2 |
| lisi | 1 |
| wangwu | 3 |
| zhangsan | 2 |
+----------+-------+
//先执行()里的select语句,把结果的集合作为前面select语句的查询条件
mysql> delete from tmp where id in (select a.id from (select id from tmp where age=20) a);
//把(select id from tmp where age=20)的结果定义别名给a
1.8: valor NULL
*空值长度为0,不占空间;NULL值的长度为NULL,占用NULL这个字符空间 NULL就好比"真空" 空值好比"空气"
//Conut计数空值会计入统计
//COUNT计数时NULL会被忽略
//空值不是NULL
mysql> select * from num where name is not null;
+----+------+
| id | name |
+----+------+
| 1 | tom |
| 3 | |
+----+------+
mysql> select * from num where name is null;
+----+------+
| id | name |
+----+------+
| 2 | NULL |
+----+------+
1.9: Expressões regulares
1.9.1: Registros começando com uma string específica
mysql> select id,name,score from accp where name regexp '^li';
1.9.2: Registros terminando com uma string específica
mysql> select id,name,score from accp where name regexp 'wu$';
1.9.3: Registros contendo a string especificada
mysql> select id,name,score from accp where name regexp 'an';
1.9.4: Use "." Para substituir qualquer registro de caractere na string
mysql> select id,name,score from accp where name regexp 'zhang.an'; //regexp英文就是正则表达式的意思
1.9.5: Registros de correspondência que contêm ou relação
mysql> select id,name,score from accp where name regexp 'an|si';
1.9.6: Corresponde a qualquer número de caracteres anteriores
mysql> insert into num (id,name) values (4,'oooo'),(5,'ooooo');
1.9.7: '+' corresponde ao caractere anterior pelo menos uma vez
mysql> select id,name from num where name regexp 'ooooo+';
1.9.8: Corresponde a qualquer um do conjunto de caracteres especificado
mysql> select id,name from num where name regexp '^[a-z]';
1,10: Operador
1.10.1: Operadores aritméticos
mysql> select 1+2,2*3,5-4,7%2,7/2;
1.10.2: Operadores de comparação
---等于运算符
mysql> select 2=4,2='2','e'='e',(2+2)=(3+1),'r'=NULL;
0 | 1 | 1 | 1 | NULL
---不等于运算符
mysql> select 'kgc'!='bdqn',12<>13,NULL<>NULL;
| 1 | 1 | NULL
---大于、大于等于、小于、小于等于运算符
条件成立返回1,不成立返回0
---IS NULL、IS NOT NULL
IS NULL 判断一个值是否为 NULL,如果为 NULL 返回 1,否则返回 0。
IS NOT NULL 判断一个值是否不为 NULL,如果不为 NULL 返回 1,否则返回 0
---BETWEEN AND
BETWEEN AND 比较运算通常用于判断一个值是否落在某两个值之间.
mysql> select 4 between 2 and 6,5 between 5 and 10,'f' between 'a' and 'z';
| 1 | 1 | 1 |
---LEAST、GREATEST (最小值,最大值)
---IN NOT IN IN在对应的列表里返回1,否则返回0 NOT IN 返回值相反
1.11: Operadores lógicos
E && AND todo 1 é 1
ou || OR vê 1 então 1
não é NÃO!
Exclusivo invertido OR XOR todos os zeros são zero, todos os 1s (diferentes de zero) são zero, um zero e um diferente de zero são 1
1.12: Cálculo do operador de bits de números binários
Operador | descrição |
---|---|
E | Bit a bit e |
~ | Negação bit a bit |
^ | XOR bit a bit |
<< | Bit shift left |
>> | Bit shift right |
Em relação à operação AND e à operação OR
// Operação E todos 1 1
1010 10
1111 15
resultado
1010 = 10
// Operação OR ver 1 1
1010
1111
resultado
1111 = 15
// operação OR exclusiva
1010
1111
resultado
0101 = 5
O operador de deslocamento para a esquerda muda para a esquerda, a parte em excesso é removida e a parte vaga é preenchida com zero. O
operador de deslocamento para a direita muda para a direita e a parte em excesso é removida.
"15 >> 2" converte o número 15 em binário que é 1111, e desloca dois bits para a direita. Os dois bits de 11 à direita são descartados e tornam-se 11, e à esquerda é preenchida com 00 e, finalmente, torna-se 0011 em binário, que é 3 quando convertido em decimal.
1111 Deslocar dois bits para a direita
11 Preencher com zeros na frente
0011
0010 Deslocar com dois bits para a esquerda
10 Preencher com zeros atrás
1000
// 5 & ~ 1 significa a operação de inversão de 5 e 1
0001 Inversão 1110
1110 A operação de soma é toda 1, então 1
0101
resultado
0100 = 4
1.13 Precedência de operadores
Operadores com níveis mais altos serão calculados primeiro. Se os operadores forem do mesmo nível, o MySQL fará os cálculos da esquerda para a direita.
prioridade | Operador | prioridade | Operador |
---|---|---|---|
1 | ! | 8 | |
2 | ~ | 9 | =, <=>,> =,>, <=, <, <>,! =, IS, LIKE, REGEXP, IN |
3 | ^ | 10 | ENTRE, CASO, QUANDO, ENTÃO, OUTRO |
4 | *, / (DIV),% (MOD) | 11 | NÃO |
5 | +, - | 12 | &&,E |
6 | >>, << | 13 | |
7 | E | 14 | : = |
"!" tem a prioridade mais alta e ": =" tem a prioridade mais baixa.
1.14 Conectar consulta
1.14.1 Intersecção de junção interna
select a.列,b.列 from a表 a(别名) inner join b表 b(别名) on a(列)=b(列);
mysql> select a.name,h.hob_name from accp a inner join Hob h on a.hobby=h.id;
+----------+--------------+
| name | hob_name |
+----------+--------------+
| wangwu | 大数据 |
| lisi | 云计算 |
| wangwu | 人工智能 |
| zhangsan | 大数据 |
+----------+--------------+
1.4.2 Conexão esquerda
左表是主表,全显示,右表是辅表,匹配到才显示,匹配不到的NULL
select a.列,b.列 from a表 a(别名) left join b表 b(别名) on a(列)=b(列);
mysql> select a.name,h.hob_name from accp a left join Hob h on a.hobby=h.id;
+----------+--------------+
| name | hob_name |
+----------+--------------+
| lisi | 云计算 |
| wangwu | 大数据 |
| zhangsan | 大数据 |
| wangwu | 人工智能 |
| zhaoliu | NULL |
| tianqi | NULL |
+----------+--------------+
1.4.2 Conexão certa
右表主表列全显示,左表匹配到的显示,匹配不到的null
select a.列,b.列 from a表 a(别名) right join b表 b(别名) on a(列)=b(列);
mysql> select a.name,h.hob_name from accp a right join Hob h on a.hobby=h.id;
+----------+--------------+
| name | hob_name |
+----------+--------------+
| wangwu | 大数据 |
| lisi | 云计算 |
| wangwu | 人工智能 |
| zhangsan | 大数据 |
| NULL | 大数据 |
+----------+--------------+