2012-01-26 63 views
0

我有表如下結構,除了在MySQL查詢條件..

name (type: TEXT) 
price (type: INT) 
color (type: TEXT) 
vehicletype (type: TEXT) eg. SEDAN/SUV 

現在我想檢索(名稱,價格,顏色,vehicletype)如果它的黑色轎車,我已經準備好支付10,000,但如果它的紅色或白色,則不超過8000。對於任何其他顏色,我不會超過7000,除非是SUV,在這種情況下,我的預算高達15,000黑色或高達14,000其他顏色。
我有這個疑問,但它沒有工作,

SELECT name, price, color, vehicletype FROM carrecords WHERE 
(vehicletype = 'SEDAN' AND color = 'black' AND price <= 10000) OR 
(vehicletype = 'SEDAN' AND color IN('red','white') AND price <= 8000) OR 
(vehicletype = 'SEDAN' /* here I tried != "SUV" as well - no luck*/ AND color NOT IN('red','white','black') AND price <= 7000) OR 
(vehicletype = 'SUV' AND color = 'black' AND price <= 15000) OR 
(vehicletype = 'SUV' AND color != 'black' AND price <= 14000) 
ORDER BY price ASC 

是這樣,有什麼解決辦法?

回答

4
SELECT name, price, color, vehicletype FROM carrecords WHERE 
-- black sedans up to 10k 
(vehicletype = 'SEDAN' AND color = 'black' AND price <= 10000) 
-- red or white sedans up to 8k 
OR (vehicletype = 'SEDAN' AND color IN('red','white') AND price <= 8000) 
-- black SUV up to 15k 
OR (vehicletype = 'SUV' AND color = 'black' AND price <= 15000) 
-- non-black SUV up to 14k 
OR (vehicletype = 'SUV' AND color != 'black' AND price <= 14000) 
-- any other vehicle up to 7k 
OR (price <= 7000) 
ORDER BY price ASC 
+0

不錯。 'color!='black''可以省略。 –

+0

@ypercube是的,它可以 - 評論也是如此。我希望代碼以簡潔和優化爲代價顯示我的意圖(取決於DB中的汽車,價格<= 7000'首先可能是一個直接的加速) –

+0

是的,它的工作原理.. .thanks –