繁体   English   中英

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

[英]Select records in on table based on conditions from another table?

我有2张桌子,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
)

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

UPDATE

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

SELECT B.*
FROM B
WHERE B.type_id
IN 
( SELECT A.type_id 
  FROM A WHERE status='True'
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM