mybatis的使用技巧8——联合查询union和union all的区别和用法

在实际项目开发中,会经常联合查询结构相似的多张数据表,使用union关键字就只需要一次sql操作,而无需执行多次查询并通过代码逻辑合并处理,减少了大量繁琐的操作,最重要的是还能通过可选的all关键字筛选重复的数据。

1.union和union all区别

  • 相同点:两者都用于把来自多个select语句的结果组合到一个结果集合中。
  • 不同点:当使用union时,mysql会把结果集中重复的记录删掉,而使用union all ,mysql会把所有的记录返回,且效率高于union。

最终的查询结果对比:

2.union和union all用法

重要的注意事项:

  • 第一个select语句中被使用的字段名称会被用于最终结果集的字段名称。
  • 存在union关键字的sql语句仅属于一条完整的sql,因此每一个select语句结束后都不能写标点符号。
  • 在多个 SELECT 语句中,对应的列应该具有相同的字段属性且同时字段的顺序要保持一致。
  • 如果子句中有order by,limit,需用括号()包起来。推荐放到所有子句之后,即对最终合并的结果来排序或筛选。

具体的写法如下:

sql 复制代码
-- union
select id,logo_sn sn
from card_info 
where del_flag = '0'
and id in (57,72)
union 
select helmet_id id,helmet_sn sn
from use_log
where del_flag = '0'
and helmet_id in (57,72)

-- union all
select id,logo_sn sn
from card_info 
where del_flag = '0'
and id in (57,72)
union all 
select helmet_id id,helmet_sn sn
from use_log
where del_flag = '0'
and helmet_id in (57,72)
相关推荐
8***848212 小时前
spring security 超详细使用教程(接入springboot、前后端分离)
java·spring boot·spring
9***J62812 小时前
Spring Boot项目集成Redisson 原始依赖与 Spring Boot Starter 的流程
java·spring boot·后端
M***Z21012 小时前
SQL 建表语句详解
java·数据库·sql
v***79412 小时前
Spring Boot 热部署
java·spring boot·后端
执笔论英雄12 小时前
【RL】python协程
java·网络·人工智能·python·设计模式
galaxyffang12 小时前
认证、会话管理、授权的区别
java
未名编程12 小时前
Windows 下如何部署 Nacos 并导入配置文件
java·windows
boonya13 小时前
Java中Plugin设计模式的规范应用
java·spring·设计模式·插件模式
小兔薯了13 小时前
7. LNMP-wordpress
android·运维·服务器·数据库·nginx·php
瑞思蕊萌13 小时前
redis实战篇--完结篇
数据库·redis·缓存