2014-10-20 66 views
0

你能否帮我查询数据库,我需要选择具有相同组合ID的产品。 例如产品ID为70和75.他们都有过滤器1和12.SQL选择:适合两个ID的

IN不会工作,它也将#66 cuz它有过滤器1那里,但第二个是11,那不是我所需要的....

product_id | filter_id 
    ______________________ 
    66   | 1 
    66   | 11 
    68   | 9 
    69   | 13 
    70   | 1 
    70   | 12 
    71   | 14 
    72   | 4 
    72   | 17 
    73   | 7 
    73   | 14 
    74   | 16 
    75   | 1 
    75   | 12 
+0

你想获得与过滤器1'元素和下面的获得是重复的筛选器列表的名单,与他们的产品列表一起'12? – 2014-10-20 10:44:12

+0

你的问题不够清楚。可以过滤器超过2?另外,预期的结果是什么?你想要与过滤器ID一起,或者没有... – 2014-10-20 10:46:06

回答

0

试试这个:

SELECT t1.* 
    FROM table AS t1 
    JOIN table AS t2 ON t1.product_id = t2.product_id 
WHERE t1.filter = 1 
    AND t2.filter = 12 
+0

工作伟大!谢谢你的快速回答! – 2014-10-20 10:58:36

0
SELECT Product_ID 
,  Filter_ID 
FROM Your_Table a 
WHERE Filter_ID = 1 
    AND EXISTS (
       SELECT  NULL 
       FROM  Your_Table b 
       WHERE  Filter_ID = 12 
         AND b.Product_ID = a.Product_ID 
       ) 
0

如果你想有完全相同的IDS(而不是专门1和12)对,然后我会建议使用group_concat()到列出ID,然后加入以找到重复项。具有

select filters, count(*) as numdups, group_concat(product_id) as products 
from (select product_id, group_concat(filter_id order by filter_id) as filters 
     from table t 
     group by product_id 
    ) pf 
where count(*) > 1; 
0

您可以使用组:

SELECT 
    product_id, 
    COUNT(*) cnt 
FROM 
    tablename 
WHERE 
    filter_id IN (1,12) 
GROUP BY 
    product_id 
    HAVING COUNT(*) = 2 
+0

Peraphs您在COUNT中添加了DISTINCT – 2014-10-20 10:52:11