2013-08-28 45 views
2

我有一個表「optionsproducts」具有下列結構和值檢查單個列的MySQL

ID  OptionID  ProductID 
1  1    1 
1  2    1 
1  3    1 
1  2    2 
1  2    3 
1  3    3 

現在我想提取ProductIDs針對其中兩個OptionID 2和OptionID 3被分配。這意味着在這種情況下應返回ProductID 1和3。我不知道我錯過了什麼。任何幫助將不勝感激。使用上(列名),由列名的順序不同

ProductID 
----------- 
1 
3 

回答

4

要獲得productID S的涉及到這兩個2個3 OptionId S,你可以寫一個類似的查詢:

select productid 
    from (select productid 
       , optionid 
       , dense_rank() over(partition by productid 
            order by optionid) as rn 
      from t1 
      where optionid in (2,3) 
     ) s 
where s.rn = 2 

結果:

PRODUCTID 
---------- 
1 
3 

SQLFiddle Demo

+0

非常感謝 –

1
SELECT DISTINCT ProductID FROM table WHERE OptionID IN(2,3); 
+0

我想提取OptionID 2和OptionID 3分配給的ProductID。您的查詢還將返回ProductID 2,其中根據我的要求返回ProductID 1和3 –

2

嘗試這一個 -

DECLARE @temp TABLE 
(
     ID INT 
    , OptionID INT 
    , ProductID INT 
) 

INSERT INTO @temp (ID, OptionID, ProductID) 
VALUES 
    (1, 1, 1),(1, 2, 1), 
    (1, 3, 1),(1, 2, 2), 
    (1, 2, 3),(1, 3, 3),(1, 3, 3) 

SELECT ProductID 
FROM @temp 
WHERE OptionID IN (2,3) 
GROUP BY ProductID 
HAVING COUNT(*) > 1 

輸出。

select distinct on (column_name) require field order by that column name 
+0

我已經試過了。這也返回ProductID 2.其中,因爲我需要查詢返回ProductID 1和3.事情是我需要產品id對OptionID 2和optionid 3分配。 –