嵌套连接vs并排连接

时间:2018-06-11 10:01:56

标签: sql

想象你有三张桌子:

  • 目标:使用这些列
    • ID
    • other_tb_id(外键)
    • 其他没有外键列
  • other_tb:包含以下列:
    • ID
    • other_tb2_id(外键)
    • some_col_deleted
    • 其他没有外键列
  • other_tb2:包含以下列:
    • ID
    • 其他没有外键列

1-现在这两个连接查询之间有任何区别(性能,可读性等):

select * from target_tb
    inner join (
        select * from other_tb where some_col_deleted = false
    ) other_tb on target_tb.other_tb_id = other_tb.id
    inner join other_tb2 on other_tb.other_tb2.id = other_tb2.


select * from target_tb
    inner join (
        select * from other_tb
           inner join other_tb2 on other_tb.other_tb2.id = other_tb2.id where some_col_deleted = false
    ) other_tb on target_tb.other_tb_id = other_tb.id

2-如果我将where子句放在内连接之外,我也有这个问题,它有什么不同吗?

1 个答案:

答案 0 :(得分:0)

您通常会将这些查询编写为:

select . . .
from target_tb t inner join
     other_tb o
     on t.other_tb_id = o.id inner join
     other_tb2 o2
     on o2.other_tb2.id = o2.?
where o.some_col_deleted = false;

不同版本的性能在不同的数据库中应该非常相似。运行查询的一部分是优化阶段。

请注意,表别名使查询更易于编写和阅读。

相关问题