sql查询连接多个表-太慢

dfty9e19  于 2021-06-24  发布在  Hive
关注(0)|答案(1)|浏览(299)

我目前正在尝试将几个表连接在一起(如果可能的话,还可以连接另外两个表),但是现在我的查询是如何编写的,我甚至看不到有3个表的结果

select t1.x, 
t1.y,
t1.z,
t4.a,
t4.b,
t4.c,
t4.d
from  t1
left join t2 on t1.id=t2.id
left join t3 on t2.id=t3.id
left join t4 on t1.id2=t4.id
where t1.date between 'x' and'x'
and t1.city not in ('x')
and t3.column = x;

有没有办法优化这段代码,使其运行得更快,甚至可以向其中添加更多的表?
提前谢谢!

b4lqfgs4

b4lqfgs41#

您的查询有一些逻辑问题,可能有助于提高速度。
t2与t1具有相同的id值时连接。t3被拉入,当且仅当,t2中有一行,它的值与t1和t2相同。最后,在where子句中,t3.column必须是x,否则它将被过滤。
这意味着t3中必须存在一行。每个没有t2记录和t3记录的t1记录都会被过滤掉。因此你不需要左连接,你需要一个内部连接。

select t1.x, 
t1.y,
t1.z,
t4.a,
t4.b,
t4.c,
t4.d
from  t1
inner join t2 on t1.id=t2.id
inner join t3 on t2.id=t3.id
left join t4 on t1.id2=t4.id
where t1.date between 'x' and'x'
and t1.city not in ('x')
and t3.column = x;

在某些dbms中,可以将t3.column子句移动到join命令,这有助于在计划的前面过滤掉行。

select t1.x, 
t1.y,
t1.z,
t4.a,
t4.b,
t4.c,
t4.d
from  t1
inner join t2 on t1.id=t2.id
inner join t3 on t2.id=t3.id and t3.column = x
left join t4 on t1.id2=t4.id
where t1.date between 'x' and'x'
and t1.city not in ('x');

我最后的建议是仔细看看t2,看看你是否真的需要它。扪心自问,有没有一个原因,一行必须存在于t2为了我得到正确的结果。。。因为如果t1.id=t2.id,那么t1.id=t3.id,就可以完全消除t2表。

相关问题