2015-06-29 54 views
1

我有兩個表:轉換嵌套查詢加盟

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) 

但它很慢。

所以我想嘗試將其轉換爲使用聯接而不是嵌套查詢。

+1

價值,我認爲這是不可能的* *無子查詢。當然有不同的解決方案... –

+0

我爲entry_id的代碼和索引建立索引,但仍然很慢 – Ibraheem

+0

不知道你在使用什麼RDMS,但T-SQL有各種工具來幫助建議有用的索引。我假設其他數據庫具有類似的功能。您可以使用它們來更好地定位您的索引。 –

回答

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
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 
    ) 

加入條目表只有當你需要顯示從條目表