我有两张桌子:
entry
id
......
individual
id,
entry_id,
code
其中entry
与individual
有一对多关系。
我想选择属于包含超过3个人的条目的所有个人,其代码在A = 10和B = 15之间
我写了这个查询并且有效:
select entry_id,id
from individual as i
where i.entry_id in
(select entry_id
from individual as v
where v.code between 10 and 15
group by entry_id
having count(*) > 3 )
但它很慢。
所以我想尝试将其转换为使用连接而不是嵌套查询。
答案 0 :(得分:1)
这是一个加入版本,但我不确定它是否会比嵌套查询解决方案更快。
select i1.entry_id, i1.id
from individuals as i1
join individuals as i2
on (i1.entry_id = i2.entry_id)
where i2.vcode between 10 and 15
group by i1.entry_id, i1.id
having count(*) > 3;
请注意,如果id
或(id, entry_id
)是表individuals
的主要/唯一键,此查询仅等同于您的查询。
答案 1 :(得分:1)
select
entry_id,
id,
code
from
individuals as i1
where
vcode between 10 and 15
And entry_id in (
select entry_id from individuals group by entry_id having count(entry_id) > 3
)
仅当您需要显示条目表
中的值时才加入条目表