2013-01-13 102 views
3

我有一個表格幫助選擇產品。具有多個AND或WHERE條件的複雜MySQL查詢

我想有一個查詢,我回來的每個記錄其中:

category_id = 'M10' and band_id = '010' 
OR 
category_id = 'M10' and band_id = '020' 

AND 

category_id = 'M50' and band_id = '010' 
OR 
category_id = 'M50' and band_id = '020' 

我的查詢:

SELECT 
product.entry_id AS entry_id, 
helpme.item_id AS product_id 
FROM inbound_help_me_choose helpme 
LEFT JOIN exp_channel_titles product ON (product.product_id = helpme.item_id) 
WHERE 
helpme.submarket_id = 'NZ' 
AND 
(
(helpme.category_id = 'M10' AND helpme.band_id = '010') 
OR 
(helpme.category_id = 'M10' AND helpme.band_id = '020') 
) 

正常工作的第一類,但只要我添加新的WHERE條件失敗:

SELECT 
product.entry_id AS entry_id, 
helpme.item_id AS product_id 
FROM inbound_help_me_choose helpme 
LEFT JOIN exp_channel_titles product ON (product.product_id = helpme.item_id) 
WHERE 
helpme.submarket_id = 'NZ' 
AND 
(
(helpme.category_id = 'M10' AND helpme.band_id = '010') 
OR 
(helpme.category_id = 'M10' AND helpme.band_id = '020') 
) 
AND 
(
(helpme.category_id = 'M50' AND helpme.band_id = '010') 
OR 
(helpme.category_id = 'M50' AND helpme.band_id = '020') 
OR 
(helpme.category_id = 'M50' AND helpme.band_id = '030') 
) 

對我來說這似乎沒問題,所以我完全失去了爲什麼它不工作。

+0

即使每個人都知道ANDs在條件邏輯中的ORs之前獲得了先行優先權,但我總是建議使用括號來澄清,特別是一旦您開始獲得條款中的兩個或三個條件。 – Ray

回答

3

我認爲你需要這個

SELECT 
product.entry_id AS entry_id, 
helpme.item_id AS product_id 
FROM inbound_help_me_choose helpme 
LEFT JOIN exp_channel_titles product ON (product.product_id = helpme.item_id) 
WHERE 
helpme.submarket_id = 'NZ' 
AND 
(
    (helpme.category_id = 'M10' AND helpme.band_id IN ('010','020')) OR 
    (helpme.category_id = 'M50' AND helpme.band_id IN ('010','020','030')) 
) 
+0

謝謝,這解決了我的問題。 – Csanad

+0

接受我的答案作爲答案,如果它幫助你解決你的問題 –

+0

@rs。你的查詢修正了他的邏輯(假設在問題開始時條件邏輯中顯示的是真正想要的/預期的) – Ray

0

x AND y運營商意味着需要在同一時間,以滿足既適用的xy條件。您只需要使用OR運算符。

1

改變一點點你所需要的:

category_id = 'M10' and band_id = '010' OR category_id = 'M10' and band_id = '020' 
AND 
category_id = 'M50' and band_id = '010' OR category_id = 'M50' and band_id = '020' 

是一樣的:

category_id = 'M10' and (band_id = '010' OR band_id = '020') 
AND 
category_id = 'M50' and (band_id = '010' OR band_id = '020') 

是一樣的:

category_id = 'M10' and category_id = 'M50' 
AND 
(band_id = '010' OR band_id = '020') and (band_id = '010' OR band_id = '020') 

category_id不能同時M10M50所以你不會得到任何結果...

1

你在你的問題顯示出第二個例子查詢中的WHERE子句中的條件下,一個與它的where子句中的問題打,不能從單獨計算爲true ...

第一where子句第一個示例要求category_id等於M10。

然後在第二個例子中,where子句用'和'獲得另一組語句。問題是這個where子句只想要一個category_id爲M50的記錄

無論邏輯上有什麼其他問題,我都可以相當肯定地說,你不會在同一個記錄中找到M10和M50的category_id在相同的記錄時間。

另一個用戶,@rs。用一個修改過的where子句發佈了一個查詢,該查詢符合開始或問題中指定的條件邏輯規則。