当前位置:网站首页>MySQL查询列必须和group by字段一致吗?
MySQL查询列必须和group by字段一致吗?
2022-07-27 16:13:00 【java 分享官】
目录
- 场景:查询各部门薪水最高的员工。
- MySQL group by是如何决定哪一条数据留下的?
- 那么target list和group by column不匹配就一定不能执行吗?
MySQL版本:8.0.27
场景:查询各部门薪水最高的员工。
CREATE TABLE `employee` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`dept` int NOT NULL COMMENT '部门',
`user` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '员工',
`salary` int NULL DEFAULT NULL COMMENT '薪水',
`is_deleted` tinyint(1) NOT NULL DEFAULT 0 COMMENT '是否删除',
`remark` varchar(512) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '备注',
`modify_time` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3) COMMENT '修改时间',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '员工' ROW_FORMAT = Dynamic;
INSERT INTO `employee` VALUES (1, 1, '张三', 1000, 0, NULL, '2021-12-23 09:20:19.606');
INSERT INTO `employee` VALUES (2, 1, '李四', 1500, 0, NULL, '2021-12-23 09:20:21.679');
INSERT INTO `employee` VALUES (3, 1, '王五', 2000, 0, NULL, '2021-12-23 09:20:23.371');
INSERT INTO `employee` VALUES (4, 2, '赵六', 1000, 0, NULL, '2021-12-23 09:21:59.373');
INSERT INTO `employee` VALUES (5, 2, '孙七', 1500, 0, NULL, '2021-12-23 09:22:15.000');SELECT * FROM employee ;

方法一:
SELECT
t1.*
FROM
employee t1
LEFT JOIN employee t2 ON t2.dept = t1.dept AND t1.salary < t2.salary
WHERE
t2.salary IS NULL;
方法二:
SELECT
*
FROM
( SELECT * FROM `employee` ORDER BY dept, salary DESC LIMIT 1000 ) t
GROUP BY
dept;(不加limit可能会失效)

看起来结果是一样的,但第二种其实是会有问题的。
MySQL group by是如何决定哪一条数据留下的?
MySQL通过sql_mode来提供SQL语句的合法性检查,
在默认情况下,MySQL允许查询列target list中出现除了group by column、聚集函数等以外的表达式。
但是,那些不参与group by的字段具体会返回哪条数据的值在MySQL中是处于未定义规则的状态,
MySQL不承诺一定会返回哪条数据。
分组前的数据:
SELECT * FROM employee ORDER BY dept, salary DESC LIMIT 1000;

看起来方法二返回的是每个分组中的第一条的数据,
但实际上还会与存储引擎、物理位置、索引等有关,
如果是InnoDB的话,取决于在B+Tree上命中的第一条索引,
这里不展开说明,毕竟不是安全的用法,
有的时候可能返回的结果并不是我们想要的。
关于B+Tree,可以看下这篇文章:
通过B+Tree平衡多叉树理解InnoDB引擎的聚集和非聚集索引
所以对于target list中出现的不明确的列,MySQL是不确定哪一条数据留下的。
对于语法限制比较严格的数据库,都不支持target list中出现语义不明确的列,
MySQL中提供了一个修正的sql_mode,ONLY_FULL_GROUP_BY。
SET SESSION sql_mode = 'ONLY_FULL_GROUP_BY';再执行方法二的SQL就被拒绝了:
SELECT
*
FROM
( SELECT * FROM `employee` ORDER BY dept, salary DESC LIMIT 1000 ) t
GROUP BY
dept
> 1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 't.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
> 时间: 0s'only_full_group_by'模式下MySQL会对target list和group by column中的基础列、表达式、别名列进行严格匹配。
那么target list和group by column不匹配就一定不能执行吗?
我们看下另外一条SQL:
# 订单
CREATE TABLE `order` (
`order_id` int NOT NULL AUTO_INCREMENT COMMENT '订单ID',
`order_amount` int NULL DEFAULT NULL COMMENT '订单金额',
PRIMARY KEY (`order_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '订单' ROW_FORMAT = DYNAMIC;
INSERT INTO `order` VALUES (1, 100);
INSERT INTO `order` VALUES (2, 103);
INSERT INTO `order` VALUES (3, 100);
# 订单明细
CREATE TABLE `order_detail` (
`order_detail_id` int NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`order_id` int NOT NULL COMMENT '订单ID',
`goods` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '商品名称',
`goods_amount` int NOT NULL COMMENT '商品金额',
PRIMARY KEY (`order_detail_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '订单明细' ROW_FORMAT = DYNAMIC;
INSERT INTO `order_detail` VALUES (1, 1, '苹果', 10);
INSERT INTO `order_detail` VALUES (2, 1, '橙子', 20);
INSERT INTO `order_detail` VALUES (3, 1, '香蕉', 70);
INSERT INTO `order_detail` VALUES (4, 2, '橘子', 50);
INSERT INTO `order_detail` VALUES (5, 2, '菠萝', 53);查询订单中所有商品
SELECT
t1.order_id,
t1.order_amount,
GROUP_CONCAT( t2.goods, t2.goods_amount )
FROM
`order` t1
LEFT JOIN order_detail t2 ON t2.order_id = t1.order_id
GROUP BY
t1.order_id;
这条SQL的target list和group by column并不是严格匹配的,但是也可以执行,
注意
t1.order_id是订单表的主键。
所以在'only_full_group_by'模式下,如果MySQL可以确定target list中所有列的返回值,
那么,即使target list和group by column中的基础列、表达式、别名列等不严格匹配,
MySQL也会认为它的语义是明确的,因此该条语句可以顺利通过。
原文
http://www.cnblogs.com/captaincat/
边栏推荐
- MySQL four locks
- Binary tree concept
- [MIT 6.S081] Lec 10: Multiprocessors and locking 笔记
- 2021.8.1笔记 数据库设计
- Three consecutive high-frequency interview questions of redis online celebrity: cache penetration? Cache breakdown? Cache avalanche?
- [MIT 6.S081] Lab 5: xv6 lazy page allocation
- multi-table query
- JDBC学习 Day1:JDBC
- 2021.7.19 notes DML
- Error launching IDEA
猜你喜欢

2021.7.17笔记 mysql其他命令

2021.7.18笔记 mysql数据类型

Deep learning - VIDEO behavior recognition: paper reading - two stream revolutionary networks for action recognition in videos

2021.7.19笔记 DML

MySQL learns the relationship between Day2 Sorting Query / aggregation function / grouping query / paging query / constraint / multiple tables
![[mit 6.s081] LEC 9: interrupts notes](/img/b6/a8d39aa7ede4eb1c5a74e6d15b3b1c.png)
[mit 6.s081] LEC 9: interrupts notes

2021.7.22笔记 约束

深度学习:GAN优化方法-DCGAN案例
![[MIT 6.S081] Lab 5: xv6 lazy page allocation](/img/f6/8b619412bc6ba425d0f04629917e80.png)
[MIT 6.S081] Lab 5: xv6 lazy page allocation

2021.8.9 note request
随机推荐
微信小程序获取openId, sessionKey, unionId
2021.7.28 notes
一个案例理解mysql视图
2021.7.12 internal and external connection of notes
深度学习:GAT
Marvell announced the roadmap of its arm server chip, and the performance of the next generation will be twice that of thunderx2
Preliminary introduction to C miscellaneous lecture linked list
Graphical interface programming
Software installation related
uniapp H5跨域问题
@Considerations for query of convert annotation in JPA
File path read
1. opencv图片基础操作
[mit 6.s081] LEC 3: OS organization and system calls notes
[MIT 6.S081] Lab 6: Copy-on-Write Fork for xv6
[mit 6.s081] LEC 9: interrupts notes
Uniapp has no effect on the page selector on the app side
Dynamic linked list 4 one-way circular linked list (loopsingle Implementation)
Here comes the first 5g SOC of MediaTek! A77+g77+apu3.0, officially released on November 26!
[MIT 6.S081] Lab 11: networking