2013-05-20 48 views
1

選擇我目前使用的是選擇中的選擇,以檢查是否在表中存在的數據:內選擇慢

select 
    a.id, 
    a.desc, 
    a.serial, 
    a.partno, 
    a.maintact, 
    a.lcnalc, 
    a.datedue, 
    a.intrem, 
    a.lifetype, 
    (select b.id from assets b where 
     (b.maintact = a.maintact) and 
     (b.aircraft_id = a.aircraft_id) and 
     (b.inittype = "STRT") and 
     (b.initlcnalc = a.lcnalc OR b.initlcnalc = "")) as parent 
    from assets a where aircraft_id = 6; 

我想知道的是一種更有效的方式做到上面的查詢?

回答

2

嘗試使用JOIN它會更快:

select 
    a.id, 
    a.desc, 
    a.serial, 
    a.partno, 
    a.maintact, 
    a.lcnalc, 
    a.datedue, 
    a.intrem, 
    a.lifetype, 
    b.id 
from assets a 
join assets b 
    ON (b.maintact = a.maintact) and 
    (b.aircraft_id = a.aircraft_id) and 
    (b.inittype = "STRT") and 
    (b.initlcnalc = a.lcnalc OR b.initlcnalc = "") 
where a.aircraft_id = 6; 
+1

順便說一句,一旦添加了'(b.inittype =「STRT」)''常量條件,'LEFT JOIN'就會衰變成一個普通的'JOIN'。 – wildplasser

+0

@wildplasser是的你是對的,我錯過了,thx – Stephan

0

你需要用left join要做到這一點,以確保你從assets所有行。下面是接近你想要什麼:

select 
    a.id, 
    a.desc, 
    a.serial, 
    a.partno, 
    a.maintact, 
    a.lcnalc, 
    a.datedue, 
    a.intrem, 
    a.lifetype, 
    b.parent 
from assets a left outer join 
    (select maintact, aircraft_id, lcnalc, id 
     from assets a 
     group by maintact, aircraft_id, lcnal 
    ) b 
    on b.maintact = a.maintact) and 
     (b.aircraft_id = a.aircraft_id) and 
     (b.inittype = 'STRT') and 
     (b.initlcnalc = a.lcnalc) 
where a.aircraft_id = 6; 

需要說明的是表達b.initlcnalc = a.lcnalc OR b.initlcnalc = ""。我不確定這個應該做什麼。它很可能會在您的輸出中引入重複的行。您可能需要第二次加入來處理這種情況。