2014-01-15 136 views
0

我試圖選擇在一系列類別中找到的產品,並且該產品是在過去4個月內創建的。我這樣做與此mysql - 從同一個表列中選擇多個範圍

select DISTINCT category_skus.sku, products.created_date from category_skus 
LEFT JOIN products on category_skus.sku = products.sku 
WHERE category_code > ‘70699’ and category_code < ‘70791’ 
and products.created_date > 「2013-09-13」; 

這是結果:

+------------+------------+ 
|sku   |created_date| 
+------------+------------+ 
|511-696004PU|2014-01-07 | 
+------------+------------+ 
|291-280  |2013-12-04 | 
+------------+------------+ 
|89-80  |2013-10-07 | 
+------------+------------+ 
|490-1137 |2013-11-21 | 
+------------+------------+ 

不過,我需要選擇在category_code表內的多個範圍。我不需要從'70699'到'70791'搜索,而是需要在'60130'和'60420'中進行搜索(這不是一個範圍,而是與第一類範疇相關的附加單個類別)。我的嘗試最後卻出現「空集(0.00秒):

select DISTINCT category_skus.sku, products.created_date from category_skus 
LEFT JOIN products on category_skus.sku = products.sku 
WHERE (category_code BETWEEN ‘70699’ and ‘70791’) 
and WHERE category_code = ‘60130’ and products.created_date > 「2013-09-13」; 

我在做什麼錯在這裏???我希望我解釋得很清楚,並感謝所有幫助

回答

0

where category_code in (select category_code from category_skus where (category_code  between '70699' and '70791') or (category_code in ('60130','60420'))) 
and products.created_date > ... 

工作?不知道我是否正確理解了這個問題。

+0

感謝Scraatz!您的建議似乎已經奏效!我感謝您的幫助。 – ballr

0

你的條件! 70699-70791之間不會有任何產品,也就是60130.嘗試在您自己的AND語句中嵌套您的category_code條件:

SELECT DISTINCT category_skus.sku, products.created_date 
FROM category_skus 
LEFT JOIN products ON category_skus.sku = products.sku 
WHERE products.created_date > '2013-09-13' 
AND (
    category_code BETWEEN '70699' AND '70791' 
OR category_code = '60130' 
) 
+0

如果我在這裏使用了OR,它只會拉動產品一次,如果它在多個類別? – ballr

+0

是的,因爲你正在使用'DISTINCT'。 – bdf

0

有很多方法可以做到這一點。一個簡單的查詢,你可以嘗試: -

select x.* from (
select DISTINCT category_skus.sku, products.created_date from category_skus 
LEFT JOIN products on category_skus.sku = products.sku 
WHERE category_code BETWEEN '70699' and '70791' 

union all 

select DISTINCT category_skus.sku, products.created_date from category_skus 
LEFT JOIN products on category_skus.sku = products.sku 
WHERE category_code = '60130' or catagory_code='60420' 

)x where x.created_date > "2013-09-13" 

OR

select DISTINCT s.sku, p.created_date from category_skus s 
LEFT JOIN products p on s.sku = p.sku 
WHERE s.category_code BETWEEN '70699' and '70791' or (s.catagory_code='60130' or s.catagory_code='60420') and 
p.created_date > "2013-09-13" 

希望它會幫助你。

+0

對於第一個建議,我得到一個[-bash:語法錯誤附近的意外標記'from']錯誤。我得到[-bash:語法錯誤附近的意外令牌'(']爲您的第二個建議 – ballr