在 MySQL 数据库中进行多表联合查询时,时常会碰到有重复值的情况,需要去重操作。下面介绍几种去重方法。
1. 使用distinct关键字
SELECT DISTINCT *
FROM table1
JOIN table2
ON table1.id = table2.id;
2. 使用GROUP BY
SELECT *
FROM table1
JOIN table2
ON table1.id = table2.id
GROUP BY table1.id;
3. 使用子查询
SELECT *
FROM (SELECT *
FROM table1
GROUP BY id) sub1
JOIN (SELECT *
FROM table2
GROUP BY id) sub2
ON sub1.id = sub2.id;
DISTINCT 与 ORDER 联合使用时,用于排序的字段(order by sort_num)必须要在 select list 里,否则会抛出类似下面的 MySQL 异常提示:
Caused by: java.sql.SQLException: Expression #1 of ORDER BY clause is not in SELECT list, references column 'xxx.x.sort_num' which is not in SELECT list; this is incompatible with DISTINCT
解决步骤:
1. 查看是否开启了 ONLY_FULL_GROUP_BY 规则校验
SELECT @@GLOBAL.sql_mode;
// 查询结果:
ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
SELECT @@SESSION.sql_mode;
// 查询结果:
ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
2. 关闭 ONLY_FULL_GROUP_BY 规则校验
// 去掉“ONLY_FULL_GROUP_BY,”后的值
set @@GLOBAL.sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
set @@SESSION.sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
3. 重启 MySQL 服务器
# 该令如执行失败,会提示:Redirecting to /bin/systemctl start mysql.service
service mysqld start;
# 上面命令如果执行失败,可改用此命令
systemctl start mysqld