假设有若干张表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