当前位置:网站首页>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/
边栏推荐
- uniapp 在app端page选择器没有效果
- 2021.7.13 note sub query
- Wechat applet wxacode.getunlimited generates applet code
- Announcing the acquisition of 30% shares of Wenye, what is the general intention of Dalian United?
- 1. OpenCV image basic operation
- XML学习 Day1 : xml / Jsoup解析器 / selector选择器 /Xpath选择器
- Disassembly of Xiaomi cc9 Pro: the cost of rear five shots is several times that of Xiaolong 855!
- Guoju spent $1.8 billion to acquire its competitor KEMET, and the transaction may be completed in the second half of next year
- C杂讲 链表初讲
- Technology sharing | quick intercom integrated dispatching system
猜你喜欢

2021.8.9 note request

Three consecutive high-frequency interview questions of redis online celebrity: cache penetration? Cache breakdown? Cache avalanche?

Deep learning: GCN (graph convolution neural network) theory learning summary

Error launching IDEA

Navicat 导出表生成PDM文件
![[MIT 6.S081] Lec 6: Isolation & system call entry/exit 笔记](/img/b3/89b3688a06aa39d894376d57acb2af.png)
[MIT 6.S081] Lec 6: Isolation & system call entry/exit 笔记

MySQL学习 Day1 DDL、DML、DQL基础查询

View port PID and end process

知识图谱 — pyhanlp实现命名体识别(附命名体识别代码)

2021.7.22 note constraints
随机推荐
Common commands of database 2
[mit 6.s081] LEC 6: isolation & system call entry/exit notes
微信小程序获取手机号
[MIT 6.S081] Lab 6: Copy-on-Write Fork for xv6
记一次 .NET 某智慧物流 WCS系统 CPU 爆高分析
2021.8.7笔记 servlet
机器学习分类任务效果评估指标大全(包含ROC和AUC)
[MIT 6.S081] Lab 11: networking
[MIT 6.S081] Lec 4: Page tables 笔记
知识图谱 — jieba、pyhanlp、smoothnlp工具实现中文分词(词性表)
机器学习——SVM训练集只有一类标签数据而引发的错误
The end of another era!
1. opencv图片基础操作
[MIT 6.S081] Lab 10: mmap
[MIT 6.S081] Lab 6: Copy-on-Write Fork for xv6
2021.8.6笔记 jsoup
[MIT 6.S081] Lab 3: page tables
[MIT 6.S081] Lec 5: Calling conventions and stack frames RISC-V 笔记
Linked list storage structure of dynamic linked list 2 stack (linkedstack Implementation)
Idea packaging war package and war package location