是否有更好的查詢來解決此問題?使用AND和OR更高性能的Oracle SQL動態查詢
1汽車有許多類型。
我想是這樣的:(PS這是不正確的,我知道)
select * from car join type on car.id = type.id_car
where type = 'SUV'
and type = '4x4'
and (type = 'blue' or type = 'red')
and type = 'US'
and (type = 'Manual' or type = 'Automatic' or 'SemiAutomatic')
and type = 'diesel' and so on.
我的解決辦法是:
select * from car
where numberOfANDType = (select count(1) from Type where car.id = type.id_car and type in ('suv', '4x4', 'us', 'diesel'))
and exists (select 1 from type where car.id = type.id_car and type in ('blue', 'red'))
and exists (select 1 from type where car.id = type.id_car and type in ('manual', 'automatic' or 'SemiAutomatic');
等。
ps:我知道AND使用條件的數量
ps2:這些條件是動態的。
Anywayz:我已經爲每個類型一個GROUP列,以及用於OR組中的類型,我在這個列中具有相同的值。 SUV的GROUP = 1,藍色的GROUP = 2,紅色的GROUP = 2等等。 因此,我對TYPE列和組中的計數進行查詢,以查看是否覆蓋了所有組。
Select id from car join type on .. where type in ('SUV', 'blue', 'red') group by id having count(distinct group) > 2;
謝謝。
ps3:多虧了所有誰低估了這個問題,你是非常友善的。
有你使用解釋計劃來查看這個查詢是否不好?如果我沒有弄錯,當你使用存在時,Oracle會使用你的類型FK指向汽車PK。 – 2012-01-27 13:41:39
目前還不清楚你試圖達到什麼樣的目標 - 你是否想要返回所有這些類型的汽車,所有這些類型的汽車,但沒有其他的汽車,所有這些類型的汽車都沒有,或者是什麼? – 2012-01-27 13:45:00
所有車型都具有AND類型,並且至少有一個來自OR組。您可以擁有任意數量的AND類型或OR組,並且在這些OR組中,您可以擁有任意數量的類型。 – 2012-01-27 13:49:10