网站首页 > 技术文章 正文
假设有若干张表tb1、tb2、tb3,查询各张表中的一些字段,若tb1和tb2中是1对1的关系,tb2和tb3是1对多的关系,若要同时查询tb1、tb2和tb3中的一些字段,对于相同的tb1和tb2对应的数据,可能会有多条查询的结果,如果只想查询tb3中对应的某一条数据,这时候sql该如何去编辑呢?
这时候有两种思路,第一种,先不查询tb3中的字段,先去查询tb1和tb2中的字段,再通过遍历结果集去单独查询tb3中的数据,这样的sql会简化,但在相同的查询条件下,用时会增加很多,因为多次查询数据库会有数据库连接的损耗;第二种,是通过一个sql去直接筛选选出分组,下面我分别列举oracle和mysql的用法
如果tb3中一个country(国家)对应的别名(short_name)有多个,
那对应的原始的sql为
select
tb1.user_id as userId,
tb1.user_name as userName,
tb2.country,
tb3.population,
tb3.short_name as shortName
from tb1,tb2,tb3 where tb1.user_id= tb2.user_id and tb2.country = tb3.country
oracle中的用法:改善sql
select
ROW_NUMBER() OVER(PARTITION BY userId,userName,country,population ORDER BY shortName DESC) rn,
tb.*
from (
select
tb1.user_id as userId,
tb1.user_name as userName,
tb2.country,
tb3.population,
tb3.short_name as shortName
from tb1,tb2,tb3 where tb1.user_id= tb2.user_id and tb2.country = tb3.country
) tb where rn = 1
mysql中的用法:改善sql
select
tb1.user_id as userId,
tb1.user_name as userName,
tb2.country,
tb3.population,
tb3.short_name as shortName
from tb1,tb2,tb3 where tb1.user_id= tb2.user_id and tb2.country = tb3.country
group by tb1.user_id,tb1.user_name,tb2.country,tb3.population
猜你喜欢
- 2025-08-26 Activiti 8.0.0 发布,业务流程管理与工作流系统
- 2025-08-26 2021年超详细的java学习路线总结—纯干货分享
- 2025-08-26 Java系统开发从入门到精通第三讲(文字版)
- 2025-08-26 Zabbix 2.4.8源码配置选项解析_zlib源码
- 2025-08-26 MyBatis动态SQL的5种高级玩法,90%的人只用过3种
- 2025-08-26 「Java知识」Mybatis的特性详解——动态SQL,拿走不谢
- 2025-08-26 基于Java实现,支持在线发布API接口读取数据库,有哪些工具?
- 2025-08-26 Linux 中的 "/etc/profile.d" 目录有什么作用 ?
- 2025-08-26 运维工作经验总结:逃离系统故障的十个心得
- 2025-08-26 说说通用报表控件_报表控件功能
你 发表评论:
欢迎- 最近发表
- 标签列表
-
- 前端设计模式 (75)
- 前端性能优化 (51)
- 前端模板 (66)
- 前端跨域 (52)
- 前端缓存 (63)
- 前端aes加密 (58)
- 前端脚手架 (56)
- 前端md5加密 (54)
- 前端路由 (61)
- 前端数组 (73)
- 前端js面试题 (50)
- 前端定时器 (59)
- Oracle RAC (76)
- oracle恢复 (77)
- oracle 删除表 (52)
- oracle 用户名 (80)
- oracle 工具 (55)
- oracle 内存 (55)
- oracle 导出表 (62)
- oracle约束 (54)
- oracle 中文 (51)
- oracle链接 (54)
- oracle的函数 (58)
- oracle面试 (55)
- 前端调试 (52)
本文暂时没有评论,来添加一个吧(●'◡'●)