Mysql非关联子查询和关联子查询

1. 非关联子查询

非关联子查询:子查询只执行一次,然后这个数据结果作为主查询的条
件进行执行,那么这样的子查询叫做非关联子查询

成对比较:示例如下:

mysql> select product_id, amount from order_detail where (order_id, user_id) in (select order_id, user_id from order where order_date = '2022-08-24');
+--------------+--------+
| product_id   | amount |
+--------------+--------+
|    1         |   10   |
|    2         |   20   |
+--------------+--------+
2 rows in set (0.03 sec)

mysql>

多行比较操作符

操作符 含义
ANY 需要和单行比较操作符(例如>)一起使用,和子查询返回的值比较,只要一个为true,则为true,否则为false
ALL 需要和单行比较操作符(例如>)一起使用,和子查询返回的值比较,需要所有为true,则为true,否则为false

示例如下:

mysql> select product_id from order_detail group by product_id having avg(amount) <=any (select avg(amount) from order_detail group by product_id);
+--------------+
| product_id   |
+--------------+
|    1         |
+--------------+
1 rows in set (0.03 sec)

mysql>

1. 关联子查询

关联子查询执行流程

  1. 处理外查询的第一行,将关联列形成一个元组,将元组传给子查询
  2. 执行子查询,得到子查询操作的值
  3. 外查询根据子查询返回的结果或结果集,进行该行数据的条件过滤
  4. 然后处理外查询的第二行,重复步骤1-3,直到外查询的所有行处理完成

示例如下:

mysql> select product_id from order_detail outer_tb where amount > (select avg(amount) from order_detail where channel = outer_tb.channel);

在order by中使用关联子查询

mysql> select order_id from order_detail outer_tb order by (select product_name from product where product_id = outer.product_id);

在update语句中使用关联子查询

mysql> update order_detail outer_tb set product_name = (select product_name from product where product_id = outer_tb.product_id);

在delete语句中使用关联子查询

扫描二维码关注公众号,回复: 16059037 查看本文章
mysql> delete from order_detail outer_tb where product_id in (select product_id from product where product_id = outer_tb.product_id);

猜你喜欢

转载自blog.csdn.net/yy8623977/article/details/126510097