当前位置:网站首页>Must the MySQL query column be consistent with the group by field?
Must the MySQL query column be consistent with the group by field?
2022-07-27 18:40:00 【Java sharing Officer】
Catalog
- scene : Check the highest paid employees in each department .
- MySQL group by How to decide which piece of data to leave ?
- that target list and group by column Can't it be executed if it doesn't match ?
MySQL edition :8.0.27
scene : Check the highest paid employees in each department .
CREATE TABLE `employee` (
`id` int NOT NULL AUTO_INCREMENT COMMENT ' Primary key ID',
`dept` int NOT NULL COMMENT ' department ',
`user` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ' staff ',
`salary` int NULL DEFAULT NULL COMMENT ' salary ',
`is_deleted` tinyint(1) NOT NULL DEFAULT 0 COMMENT ' Whether or not to delete ',
`remark` varchar(512) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT ' remarks ',
`modify_time` datetime(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3) COMMENT ' Modification time ',
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = ' staff ' ROW_FORMAT = Dynamic;
INSERT INTO `employee` VALUES (1, 1, ' Zhang San ', 1000, 0, NULL, '2021-12-23 09:20:19.606');
INSERT INTO `employee` VALUES (2, 1, ' Li Si ', 1500, 0, NULL, '2021-12-23 09:20:21.679');
INSERT INTO `employee` VALUES (3, 1, ' Wang Wu ', 2000, 0, NULL, '2021-12-23 09:20:23.371');
INSERT INTO `employee` VALUES (4, 2, ' Zhao Liu ', 1000, 0, NULL, '2021-12-23 09:21:59.373');
INSERT INTO `employee` VALUES (5, 2, ' Sun Qi ', 1500, 0, NULL, '2021-12-23 09:22:15.000');SELECT * FROM employee ;

Method 1 :
SELECT
t1.*
FROM
employee t1
LEFT JOIN employee t2 ON t2.dept = t1.dept AND t1.salary < t2.salary
WHERE
t2.salary IS NULL;
Method 2 :
SELECT
*
FROM
( SELECT * FROM `employee` ORDER BY dept, salary DESC LIMIT 1000 ) t
GROUP BY
dept;( No addition limit It may fail )

It seems that the result is the same , But there will be problems with the second one .
MySQL group by How to decide which piece of data to leave ?
MySQL adopt sql_mode To provide SQL Check the validity of the statement ,
By default ,MySQL Allow query Columns target list In addition to group by column、 Expressions other than aggregate functions .
however , Those who don't participate group by Which data value will be returned in the field of MySQL Is in the state of undefined rules ,
MySQL Do not promise which data will be returned .
Data before grouping :
SELECT * FROM employee ORDER BY dept, salary DESC LIMIT 1000;

It seems that method 2 returns the data of the first item in each group ,
But it will actually work with the storage engine 、 physical position 、 Index, etc ,
If it is InnoDB Words , It depends on B+Tree The first index hit on ,
There is no explanation here , After all, it's not safe to use ,
Sometimes the result may not be what we want .
About B+Tree, Take a look at this article :
adopt B+Tree Balanced multitree understanding InnoDB Clustered and nonclustered indexes of the engine
So for target list Ambiguous columns in ,MySQL It's not sure which piece of data is left .
For databases with strict syntax restrictions , Don't support target list Semantically ambiguous columns appear in ,
MySQL A modified is provided in sql_mode,ONLY_FULL_GROUP_BY.
SET SESSION sql_mode = 'ONLY_FULL_GROUP_BY';Then execute the... Of method 2 SQL I was rejected :
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
> Time : 0s'only_full_group_by' In mode MySQL Would be right target list and group by column The base column in 、 expression 、 Don't make a strict match .
that target list and group by column Can't it be executed if it doesn't match ?
Let's look at another one SQL:
# Order
CREATE TABLE `order` (
`order_id` int NOT NULL AUTO_INCREMENT COMMENT ' Order ID',
`order_amount` int NULL DEFAULT NULL COMMENT ' Order amount ',
PRIMARY KEY (`order_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = ' Order ' ROW_FORMAT = DYNAMIC;
INSERT INTO `order` VALUES (1, 100);
INSERT INTO `order` VALUES (2, 103);
INSERT INTO `order` VALUES (3, 100);
# The order details
CREATE TABLE `order_detail` (
`order_detail_id` int NOT NULL AUTO_INCREMENT COMMENT ' Primary key ID',
`order_id` int NOT NULL COMMENT ' Order ID',
`goods` varchar(32) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT ' Name of commodity ',
`goods_amount` int NOT NULL COMMENT ' The amount of goods ',
PRIMARY KEY (`order_detail_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = ' The order details ' ROW_FORMAT = DYNAMIC;
INSERT INTO `order_detail` VALUES (1, 1, ' Apple ', 10);
INSERT INTO `order_detail` VALUES (2, 1, ' The oranges ', 20);
INSERT INTO `order_detail` VALUES (3, 1, ' Banana ', 70);
INSERT INTO `order_detail` VALUES (4, 2, ' a mandarin orange ', 50);
INSERT INTO `order_detail` VALUES (5, 2, ' Pineapple ', 53);Query all items in the order
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;
This article SQL Of target list and group by column It's not a strict match , But it can also be done ,
Be careful
t1.order_id Is the primary key of the order table .
So in 'only_full_group_by' In mode , If MySQL Can be determined target list Return values of all columns in the ,
that , Even if target list and group by column The base column in 、 expression 、 Aliases, columns, etc. do not match strictly ,
MySQL It will also be considered that its semantics is clear , Therefore, the statement can pass .
original text
http://www.cnblogs.com/captaincat/
边栏推荐
- [MIT 6.S081] Lec 6: Isolation & system call entry/exit 笔记
- Idea packaging war package and war package location
- MySQL learning day3 multi table query / transaction / DCL
- 2021.7.22笔记 约束
- 图文结合,完美解释MySQL逻辑备份的实现流程
- [MIT 6.S081] Lab 11: networking
- 阿里架构师耗时280个小时整理的1015页分布式全栈小册,轻松入手分布式系统
- MySQL learning Day1 DDL, DML, DQL basic query
- Pandas' to_ SQL function usage
- Deep learning: GCN diagram classification case
猜你喜欢

2021.7.22 note constraints

2 万字 + 30 张图 | 细聊 MySQL undo log、redo log、binlog 有什么用?

Error launching IDEA

2021.7.18笔记 mysql数据类型

Knowledge map - Jieba, pyhanlp, smoothnlp tools to realize Chinese word segmentation (part of speech)
![[MIT 6.S081] Lab 7: Multithreading](/img/f4/26e513fb8678a88cfba29c1a636b37.png)
[MIT 6.S081] Lab 7: Multithreading

2021.8.6笔记 jsoup

Super practical! After reading the kubernetes study notes hidden by Alibaba P9, call NB directly

2. Change color space and color detection

1. opencv图片基础操作
随机推荐
搭建一个简单的知识问答系统
[MIT 6.S081] Lab 10: mmap
知识图谱 — jieba、pyhanlp、smoothnlp工具实现中文分词(词性表)
Basic operations of MySQL view
Binary tree concept
Idea packaging war package and war package location
Conflict between blur event and click event in input box
[MIT 6.S081] Lab 5: xv6 lazy page allocation
[MIT 6.S081] Lab 9: file system
Why don't you like it? It's easy to send mail in ci/cd
知识图谱 — pyhanlp实现命名体识别(附命名体识别代码)
Deep learning: installation package records
[MIT 6.S081] Lab 11: networking
文件路径读取
uniapp 在app端page选择器没有效果
[mit 6.s081] LEC 9: interrupts notes
An analysis of CPU explosion of a smart logistics WCS system in.Net
修改input中placeholder样式
2021.7.17笔记 mysql其他命令
JPA connection database password field blob