网站首页 > 技术文章 正文
假设有若干张表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-05-02 MySQL自增ID用完了怎么办?4种解决方案!
- 2025-05-02 MySQL批量插入性能对比:100、1000、10000行,谁更胜一筹?
- 2025-05-02 牛哇!MySQL中的日志“binlog”的三种格式这么好玩
- 2025-05-02 从B+树原理到实战:MySQL索引设计的22条军规
- 2025-05-02 mysql数据库基本增删改查操作总结
- 2025-05-02 MySQL索引效率太快,1亿数据查询不到1秒
- 2025-05-02 MySQL大数据表处理策略,原来一直都用错了……
- 2025-05-02 在MySQL命令行中获取用户账户列表的方法
- 2025-05-02 MySQL分库分表设计方案:大道至简,数据不乱
- 2025-05-02 从零到亿级数据:MySQL 分库分表实战避坑指南
- 最近发表
- 标签列表
-
- cmd/c (64)
- c++中::是什么意思 (83)
- 标签用于 (65)
- 主键只能有一个吗 (66)
- c#console.writeline不显示 (75)
- js判断是否空对象 (63)
- pythoncase语句 (81)
- es6includes (73)
- sqlset (64)
- phprequire_once (61)
- localstorage.removeitem (74)
- vector线程安全吗 (70)
- & (66)
- java (73)
- org.redisson (64)
- cannotinstantiatethetype (62)
- js数组插入 (83)
- gormwherein (64)
- linux删除一个文件夹 (65)
- mac安装java (72)
- outofmemoryerror是什么意思 (64)
- flask文件上传 (63)
- eacces (67)
- 查看mysql是否启动 (70)
- 无效的列索引 (74)