2009-12-04 425 views
0

我有兩個表:使用Select語句,其中X IN(SELECT ...)

[ product_to_category 
--------------------- 
product_id 
category_id 


[ category 
--------------------- 
category_id 
parent_id 

我需要把所有的product_id與 '39' 的category.parent_id。這裏就是我想要的,但如果至少有幾百它返回空:

SELECT 
product_id 
FROM 
product_to_category 
WHERE 
category_id IN (
SELECT parent_id FROM category WHERE parent_id = '39' 
) 

是什麼,我想在這裏做可能嗎?

+0

參考:http://stackoverflow.com/questions/1772609/procedurally-transform-subquery-into-join – 2009-12-04 20:43:33

回答

6

明白了:

SELECT的product_id FROM product_to_category INNER JOIN 類別在 product_to_category.category_id = category.category_id AND category.parent_id = 39

+1

一般來說,連接是無論如何,都比子查詢更快。 – steve 2009-12-04 20:44:36

0
select product_id from product_to_category as ptc 
inner join category as c 
    on ptc.category_id = c.parent_id 
where c.parent_id = 39 
2

試試這個:

SELECT product_id 
FROM product_to_category p2c 
    Join category c 
     On c.category_id = p2c.category_id 
Where parent_id = '39' 

你在做什麼錯在你的查詢是:

SELECT product_id 
FROM product_to_category 
WHERE category_id IN 
    (SELECT category_id -- THIS IS WHERE YOUR SQL WAS INCORRECT 
     FROM category WHERE parent_id = '39')