Operações de consulta rápida do MySQL em dados em tabelas

Verificação rápida do MySQL

Como muitas vezes esqueço algumas instruções, palavras-chave, operações do MySQL, etc. em meu trabalho e estudo diário, recentemente reservei algum tempo para escrever o seguinte conteúdo sobre MySQL. É como um dicionário


Redefinir senha mysql Operadores
de tipo de dados Funções comuns Integridade de dados Operações básicas do banco de dados Operações na própria tabela Este artigo subconsulta conexão de múltiplas tabelas visualização de índice pré-processamento de instruções SQL funções personalizadas e programação de procedimentos armazenados no MySQL













Inserir registro da tabela

{
   
   INSERT | REPLACE} [INTO] 表名
	[(字段名 [, 字段名, ...])]
    {
   
   VALUES | VALUE}
    ([,, ...])[,(,[,, ...]), ...]

例如向表t1插入值
表t1结构:
mysql> desc t1;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int      | NO   | PRI | NULL    |       |
| name  | char(10) | YES  | UNI | NULL    |       |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.02 sec)

# 插入一行数据
mysql> insert into t1 value(1,'老李');
Query OK, 1 row affected (0.02 sec)

mysql> insert into t1(id) values(2);
Query OK, 1 row affected (0.01 sec)

# 插入多行
mysql> insert t1 values(3, 'ab'),(4,'cd');
Query OK, 2 rows affected (0.01 sec)
Records: 2  Duplicates: 0  Warnings: 0

A diferença entre inserir e substituir

Se um ou mais campos da tabela devem ser exclusivos (não repetíveis), se você usar insert para inserir dados que já existem no campo correspondente da tabela, um erro será relatado, mas a substituição excluirá primeiro o registro original e insira o novo registro de.

mysql> desc t1;
+-------+----------+------+-----+---------+-------+
| Field | Type     | Null | Key | Default | Extra |
+-------+----------+------+-----+---------+-------+
| id    | int      | NO   | PRI | NULL    |       |
| name  | char(10) | YES  | UNI | NULL    |       |
+-------+----------+------+-----+---------+-------+
2 rows in set (0.02 sec)
# 表t1中的id是主键,主键必须唯一

# 表中的已有的记录
mysql> select * from t1;
+----+--------+
| id | name   |
+----+--------+
|  2 | NULL   |
|  3 | ab     |
|  4 | cd     |
|  1 | 老李   |
+----+--------+
4 rows in set (0.00 sec)

# 这时候用insert插入会报错
mysql> insert into t1 value(2, '老王');
ERROR 1062 (23000): Duplicate entry '2' for key 't1.PRIMARY'

# 使用replace就能成功插入
mysql> replace into t1 value(2, '老王');
Query OK, 2 rows affected (0.00 sec)
# 改变后
mysql> select * from t1;
+----+--------+
| id | name   |
+----+--------+
|  3 | ab     |
|  4 | cd     |
|  1 | 老李   |
|  2 | 老王   |  # null变成了老王
+----+--------+
4 rows in set (0.00 sec)

Mais

Excluir registro da tabela

DELETE FROM 表名 
    [WHERE where_condition]


# 原来表中内容
mysql> select * from t1;
+----+--------+
| id | name   |
+----+--------+
|  3 | ab     |
|  4 | cd     |
|  1 | 老李   |
|  2 | 老王   |
+----+--------+
4 rows in set (0.00 sec)

# 删除t1表中id为4的记录
mysql> delete from t1 where id = 4;
Query OK, 1 row affected (0.00 sec)

mysql> select * from t1;
+----+--------+
| id | name   |
+----+--------+
|  3 | ab     |
|  1 | 老李   |
|  2 | 老王   |
+----+--------+
3 rows in set (0.00 sec)


# 如果不写where条件将会删除表中所有记录(但不会把表删除)
mysql> delete from t1;
Query OK, 3 rows affected (0.01 sec)

mysql> select * from t1;
Empty set (0.00 sec)

Mais

Modificar registros da tabela

UPDATE  表名
    SET 字段名 =[, 字段名 =, ...]
    [WHERE where_condition]


# 原来的记录
mysql> select * from t1;
+----+--------+
| id | name   |
+----+--------+
|  2 | 阿七   |
|  1 | 老ok   |
+----+--------+
2 rows in set (0.00 sec)

# 将t1表中id为2的记录的name修改为‘老八’
mysql> update t1 set name = '老八' where id = 2;
Query OK, 1 row affected (0.01 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from t1;
+----+--------+
| id | name   |
+----+--------+
|  1 | 老ok   |
|  2 | 老八   |
+----+--------+
2 rows in set (0.00 sec)

# 不加where条件的话将会修改表中所有记录
mysql> update t1 set name = '九哥';
Query OK, 2 rows affected (0.00 sec)
Rows matched: 2  Changed: 2  Warnings: 0
# 注:被修改的字段不能是unique约束的,并且不能是有索引的,否则会报错.

Mais

Consultar registros da tabela

SELECT [DISTINCT]
    select_expr [, select_expr,...] 
    [FROM 表名[, 表名,...]
    [WHERE 选择条件]
    [GROUP BY {字段名 | 表达式} [WITH ROLLUP]]
    [HAVING 选择条件]
    [ORDER BY {字段名 | 表达式} [ASC | DESC]]
    [LIMIT {
   
   [偏移量(起始行),] 行数 | 行数 OFFSET 偏移量}]]
select_expr:
	字段名 [[as] 显示的字段名]
	*
	select语句 [as]select语句取的名(当做字段名)
  • desduplicação distinta
  • onde filtro (filtro)
  • grupo por grupo
  • tendo filtro, geralmente usado junto com group by. Será filtrado posteriormente após ser filtrado
  • order por padrão é ordem crescente (asc), você pode especificar asc (ordem crescente) ou desc (ordem decrescente)
  • limite limita o número de linhas
    para mais
    distintas
    , onde
    agrupar por
    ordem por
# 查询表t1中所有字段
mysql> select * from t1;
+----+--------+
| id | name   |
+----+--------+
|  1 | 九哥   |
|  2 | 九哥   |
+----+--------+
2 rows in set (0.00 sec)


# 查询表t1的记录,并限制只查一行
mysql> select * from t1 limit 1;
+----+--------+
| id | name   |
+----+--------+
|  1 | 九哥   |
+----+--------+
1 row in set (0.00 sec)

# 查询id为1的记录,并且只要name字段
mysql> select name from t1 where id = 1;
+--------+
| name   |
+--------+
| 九哥   |
+--------+
1 row in set (0.00 sec)

# 查询id大于0的记录,并降序显示
mysql> select * from t1 where id > 0 order by id desc;
+----+--------+
| id | name   |
+----+--------+
|  2 | 九哥   |
|  1 | 九哥   |
+----+--------+
2 rows in set (0.00 sec)

Consultas mais complexas serão introduzidas em artigos posteriores, como operações de junção de tabelas, subconsultas, etc.

Acho que você gosta

Origin blog.csdn.net/weixin_45345384/article/details/115680357
Recomendado
Clasificación