gpt4 book ai didi

sql - 根据另一个表中的条件选择表中的记录?

转载 作者:行者123 更新时间:2023-12-04 03:38:18 25 4
gpt4 key购买 nike

我有两张 table ,A,B

A: id is primary key and indexed

id, type_id, status
------------------
1, 1, True
2, 1, False
3, 2, False
...

B: (Type) type_id is primary key and indexed

type_id, param
----------
1, 23
2, 35
3, 24

我想选择 B 中的所有行在 A 中至少有 1 个关联条目与 status True
select distinct B.id, B.param 
from B
join A on A.type_id = B.type_id
where A.status = true

这是一个好方法吗?

最佳答案

我会这样做(在大多数数据库系统中应该是有效的:

select *
from b
where type_id in (
select type_id
from a
where status = true
)

对于您关于您的方法是否是好方法的问题,我的回答是否定的,这不是一个好方法,因为它可能会强制一个大的中间记录集(通过加入)然后在中间记录集上消耗时间。

更新

经过一番思考,我意识到没有绝对好的或坏的解决方案。这一切都取决于您在每个表中拥有的数据(总记录、值分布等...)。因此,继续使用明确传达意图的方法,并准备在生产中遇到性能问题时尝试不同的方法。

关于sql - 根据另一个表中的条件选择表中的记录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19163219/

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