2012-07-10 90 views
-2

我有以下的列的表SQL加入在同一個表

  • product_types
  • brand_ids

我需要brand_ids A和B,但不是C

在此表中,可以有多個具有相同product_type但具有不同brand_id的記錄。

難道是INNER SELF JOIN的需要嗎?還是有更好的方法來做到這一點?

+0

如果你需要數據庫的幫助,送樣本數據和預期的結果。這是最簡單的方法來幫助你,因爲我不知道你在問什麼。 – JonH 2012-07-10 19:36:19

+1

你的意思是'OR'而不是'AND'? – 2012-07-10 19:37:51

回答

4
SELECT A.product_type 
FROM product_table A 
JOIN product_table B ON A.product_type = B.product_type 
LEFT JOIN product_table C ON A.product_type = C.product_type 
         AND c.brand_id = 'C' 
WHERE A.brand_id = 'A' 
    AND B.brand_id = 'B' 
    AND c.brand_id IS NULL 
0

我打算假設(PRODUCT_TYPE, BRAND_ID)是您桌子上的唯一鍵。

這裏有一個方法做什麼,我認爲你是後:

SELECT product_type FROM product_table 
    WHERE brand_id IN ('A','B') 
    GROUP BY product_type 
    HAVING COUNT(*) = 2 
MINUS 
SELECT product_type FROM product_table 
    WHERE brand_id IN ('C') 
0

你可以試試這個解決方案:

SELECT a.product_type 
FROM 
(
    SELECT product_type 
    FROM tbl 
    WHERE brand_id IN ('A', 'B') 
    GROUP BY product_type 
) a 
LEFT JOIN tbl b ON a.product_type = b.product_type AND b.brand_id = 'C' 
WHERE b.brand_id IS NULL