gpt4 book ai didi

sql - 比较 inner join 和 where in 的用法

转载 作者:行者123 更新时间:2023-11-29 14:36:46 24 4
gpt4 key购买 nike

有两个表 - all_dataselected_place_day_hours

all_dataplace_iddayhourmetric

selected_place_day_hours 包含字段 place_iddayhour

我需要对 all_data 进行子集化,以便仅在 中记录具有 place_iddayhour 的记录selected_place_day_hours 被选中。

我可以从两个方面着手

1.使用inner join

select a.*
from all_data as a
inner join selected_place_day_hours as b
on (a.place_id = b.place_id)
and ( a.day = b.day)
and ( a.hour = b.hour)
;

2.使用where in

select *
from all_data
where
place_id in (select place_id from selected_place_day_hours)
and day in (select day from selected_place_day_hours)
and hour in (select day from selected_place_day_hours)
;

我想从功能和性能的角度了解为什么、何时、如果您会选择其中一个而不是另一个?

一个想法是,在上面的 #2 中,子选择可能对性能不友好,而且代码也更长。

最佳答案

两者在语义上是不同的。

IN 执行半连接,这意味着它从 all_data 返回一个,而不管 中匹配了多少行selected_place_day_hours

JOIN 可以返回多行。

因此,第一条建议是使用适合您要完成的任务的版本。

假设 select_place_day_hours 中的数据保证最多匹配一次,那么您会遇到性能问题。第一条建议是尝试对您的数据和系统进行查询。但是,通常 JOIN 的优化至少与 IN 一样,因此这通常是一个安全的选择。

关于sql - 比较 inner join 和 where in 的用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43220562/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com