Tutorial básico de MySQL 15 - Consulta de tabla múltiple

Tutorial básico de MySQL 15 - Consulta de tabla múltiple

Producto cartesiano

mysql> select * from user;
+----+------+--------+---------+
| id | name | gender | user_id |
+----+------+--------+---------+
|  1 | ton  | 男     |       1 |
|  2 | bom  | 女     |       2 |
|  3 | lin  | 男     |       3 |
+----+------+--------+---
mysql> select * from foot;
+----+------+
| id | s    |
+----+------+
|  1 | 苹果 |
|  2 | 香蕉 |
|  3 | 橘子 |
+----+------+
3 rows in set (0.03 sec)

// 笛卡尔积
mysql> select * from user,foot;
+----+------+--------+---------+----+------+
| id | name | gender | foot_id | id | s    |
+----+------+--------+---------+----+------+
|  1 | ton  | 男     |       1 |  1 | 苹果 |
|  2 | bom  | 女     |       2 |  1 | 苹果 |
|  3 | lin  | 男     |       3 |  1 | 苹果 |
|  1 | ton  | 男     |       1 |  2 | 香蕉 |
|  2 | bom  | 女     |       2 |  2 | 香蕉 |
|  3 | lin  | 男     |       3 |  2 | 香蕉 |
|  1 | ton  | 男     |       1 |  3 | 橘子 |
|  2 | bom  | 女     |       2 |  3 | 橘子 |
|  3 | lin  | 男     |       3 |  3 | 橘子 |
+----+------+--------+---------+----+------+
9 rows in set (0.03 sec)
复制代码

Tomando estas dos tablas como ejemplo, el fenómeno del producto cartesiano es que cada registro de la tabla A coincide con cada registro de la tabla B para formar un nuevo registro. Por ejemplo, la tabla A tiene tres registros y la tabla B tiene tres registros combinados para formar 3* 3(9) registros.

unir internamente

Los datos que muestra el producto cartesiano tendrán cosas que no necesitamos, por lo que podemos filtrar las condiciones no deseadas con condiciones.

unión interna implícita

select 字段列表 from 表1,表2 where 条件;

mysql> select * from user as u,foot as f where u.foot_id = f.id;
+----+------+--------+---------+----+------+
| id | name | gender | foot_id | id | s    |
+----+------+--------+---------+----+------+
|  1 | ton  | 男     |       1 |  1 | 苹果 |
|  2 | bom  | 女     |       2 |  2 | 香蕉 |
|  3 | lin  | 男     |       3 |  3 | 橘子 |
+----+------+--------+---------+----+------+
3 rows in set (0.03 sec)
复制代码

unión interna explícita

select 字段列表 from 表1 [inner] join 表2 on 连接条件;

mysql> select * from user as u inner join foot as f on u.foot_id = f.id;
+----+------+--------+---------+----+------+
| id | name | gender | foot_id | id | s    |
+----+------+--------+---------+----+------+
|  1 | ton  | 男     |       1 |  1 | 苹果 |
|  2 | bom  | 女     |       2 |  2 | 香蕉 |
|  3 | lin  | 男     |       3 |  3 | 橘子 |
+----+------+--------+---------+----+------+
3 rows in set (0.03 sec)
复制代码

En términos relativos, la conexión implícita es fácil de entender y escribir, la sintaxis es simple y hay menos puntos de los que preocuparse. Pero la unión explícita puede reducir el escaneo de campo y tener una velocidad de ejecución más rápida. Esta ventaja de velocidad es obvia cuando se unen 3 o más mesas.

unión externa

Agregue un nuevo registro al usuario con un foot_idcampo nulo.

mysql> select * from user;
+----+------+--------+---------+
| id | name | gender | foot_id |
+----+------+--------+---------+
|  1 | ton  | 男     |       1 |
|  2 | bom  | 女     |       2 |
|  3 | lin  | 男     |       3 |
|  4 | ken  | 女     | NULL    |
+----+------+--------+---------+
4 rows in set (0.04 sec)
mysql> select * from user,foot where user.foot_id = foot.id;
+----+------+--------+---------+----+------+
| id | name | gender | foot_id | id | s    |
+----+------+--------+---------+----+------+
|  1 | ton  | 男     |       1 |  1 | 苹果 |
|  2 | bom  | 女     |       2 |  2 | 香蕉 |
|  3 | lin  | 男     |       3 |  3 | 橘子 |
+----+------+--------+---------+----+------+
3 rows in set (0.04 sec)
复制代码

En este momento, si el campo de condición está vacío, no se consultará mediante la unión interna, por lo que podemos usar la unión externa para resolverlo.

Combinación externa izquierda (la intersección de la tabla izquierda y las tablas izquierda y derecha)

select 字段列表 from 表1 left [outer] join 表2 on 条件;

mysql> select u.*,f.* from user as u left outer join foot as f on u.foot_id = f.id;
+----+------+--------+---------+------+------+
| id | name | gender | foot_id | id   | s    |
+----+------+--------+---------+------+------+
|  1 | ton  | 男     |       1 |    1 | 苹果 |
|  2 | bom  | 女     |       2 |    2 | 香蕉 |
|  3 | lin  | 男     |       3 |    3 | 橘子 |
|  4 | ken  | 女     | NULL    | NULL | NULL |
+----+------+--------+---------+------+------+
4 rows in set (0.03 sec)
复制代码

Combinación externa derecha (la intersección de todas las tablas derechas y las tablas izquierda y derecha)

select 字段列表 from 表1 right [outer] join 表2 on 条件;

mysql> select f.*,u.* from user as u right outer join foot as f on u.foot_id = f.id;
+----+------+----+------+--------+---------+
| id | s    | id | name | gender | foot_id |
+----+------+----+------+--------+---------+
|  1 | 苹果 |  1 | ton  | 男     |       1 |
|  2 | 香蕉 |  2 | bom  | 女     |       2 |
|  3 | 橘子 |  3 | lin  | 男     |       3 |
+----+------+----+------+--------+---------+
3 rows in set (0.03 sec)
复制代码

userLa información de que la tabla ides 4 no se muestra aquí porque el footcampo de la tabla no tiene un valor nulo idcorrespondiente useral campo de la tabla.foot_id

En esencia, la combinación externa izquierda y la combinación externa derecha son iguales, siempre que se cambie la posición de la tabla, el efecto puede ser el mismo, por ejemplo:

//左外连接
select * from user as u left outer join foot as f on u.foot_id = f.id; 
//右外连接
select * from foot as f right outer join user as u on u.foot_id = f.id; 
复制代码

El efecto de la ejecución de estas dos sentencias SQL es el mismo.

auto-conexión

Las uniones automáticas se pueden usar con uniones internas y externas.

mysql> select * from yg;
+----+------+------+
| id | name | t_id |
+----+------+------+
|  1 | 张三 | NULL |
|  2 | 李四 |    1 |
|  3 | 王五 |    1 |
|  4 | 熊大 |    2 |
+----+------+------+
4 rows in set (0.05 sec)
复制代码

t_idEl campo correspondiente idrepresenta la relación superior, ahora si necesita consultar el superior correspondiente a cada persona, necesita utilizar la autoconexión.

mysql> select a.name,b.name from yg as a left outer join yg as b on a.t_id = b.id;
+------+------+
| name | name |
+------+------+
| 李四 | 张三 |
| 王五 | 张三 |
| 熊大 | 李四 |
| 张三 | NULL |
+------+------+
4 rows in set (0.03 sec)
复制代码

La unión automática es esencialmente una tabla que toma dos alias diferentes y los usa como dos tablas.

consulta conjunta

Cuando consultamos varias tablas, podemos usar la consulta de unión para recopilar datos en una tabla.

select 字段列表 from 表1 .... union[all] select 字段列表 from 表2 ...;

Supongamos que necesitamos consultar la información de la persona 2 en la tabla y la información userde la persona 3 en la tabla y resumirlos en una tabla.idygid

mysql> select u.id,u.name,u.gender from user as u where id = 2
    -> union all 
    -> select * from yg where id = 3;
+----+------+--------+
| id | name | gender |
+----+------+--------+
|  2 | bom  | 女     |
|  3 | 王五 | 1      |
+----+------+--------+
2 rows in set (0.03 sec)
复制代码

Nota: El número de campos en la lista de campos después de varias selecciones debe ser el mismo.

En algunos casos, los resultados de las dos consultas se superpondrán, si no queremos tener datos duplicados, podemos eliminarlos union.all

subconsulta

标量子查询

select * from 表1 where a = (select a from 表2 where 条件);

如果我们要查询user表中id为1的人对应foot表中的水果。

mysql> select user.foot_id from user where id = 1; 
+---------+
| foot_id |
+---------+
|       1 |
+---------+
1 row in set (0.03 sec)
mysql> select foot.s from foot where id = 1;
+------+
| s    |
+------+
| 苹果 |
+------+
1 row in set (0.02 sec)

// 标量子查询

mysql>  select foot.s from foot where id = (select user.foot_id from user where id = 1);
+------+
| s    |
+------+
| 苹果 |
+------+
1 row in set (0.04 sec)
复制代码

列子查询

子查询中数据为列。

select * from 表1 where a in (select a from 表2 where 条件)

select * from 表1 where a > all/some/any(select b from 表2 where 条件);

常用in/not in/any/some/all,其中any和some时一样的效果。

查询user表中在foot表有对应信息的信息。

mysql> select * from user where id in (select foot.id from foot);
+----+------+--------+---------+
| id | name | gender | foot_id |
+----+------+--------+---------+
|  1 | ton  | 男     |       1 |
|  2 | bom  | 女     |       2 |
|  3 | lin  | 男     |       3 |
+----+------+--------+---------+
3 rows in set (0.02 sec)
复制代码

行子查询

子查询中数据为行。

select * from 表名 where (a,b) = (select a,b from where 条件);

mysql> select * from user;
+----+------+--------+---------+
| id | name | gender | foot_id |
+----+------+--------+---------+
|  1 | 张三 | 男     |       1 |
|  2 | 李四 | 女     |       2 |
|  3 | 王五 | 男     |       3 |
|  4 | 熊大 | 女     | NULL    |
+----+------+--------+---------+
4 rows in set (0.03 sec)
mysql> select * from yg;
+----+------+------+
| id | name | t_id |
+----+------+------+
|  1 | 张三 | NULL |
|  2 | 李四 |    1 |
|  3 | 王五 |    1 |
+----+------+------+
3 rows in set (0.03 sec)

//行子查询
mysql> select * from user where (id,name) in (select yg.id,yg.name from yg);
+----+------+--------+---------+
| id | name | gender | foot_id |
+----+------+--------+---------+
|  1 | 张三 | 男     |       1 |
|  2 | 李四 | 女     |       2 |
|  3 | 王五 | 男     |       3 |
+----+------+--------+---------+
3 rows in set (0.03 sec)
复制代码

表子查询

select * from 表名 where (a,b) in (select a,b from 表名 where name = 'bom' or name = 'tom');

mysql> select * from user where (user.id,user.name) in (select yg.id,yg.name from yg where name = '张三' or name = '王五');
+----+------+--------+---------+
| id | name | gender | foot_id |
+----+------+--------+---------+
|  1 | 张三 | 男     |       1 |
|  3 | 王五 | 男     |       3 |
+----+------+--------+---------+
2 rows in set (0.04 sec)
复制代码

也可以把查询后的子表当主句查询表,例如:

select e.* , d.* from (select * from 表名 where date > '2006-5-23') e left join dept d on e.dept_id = d.id;

(点击进入专栏查看详细教程)

Supongo que te gusta

Origin juejin.im/post/7078512878214447135
Recomendado
Clasificación