使用And运算符MySQL过滤数据

时间:2015-04-21 06:53:04

标签: mysql

+-----------+-----------+
| product_id | tag_id   | 
+-----------+-----------+
|         3 |    4      |
|         3 |   29      |
|        30 |   20      | 
|         3 |   19      | 
|        30 |   19      |
+-----------+-----------+

我希望所有product_id的tag_id组合为4和19 OR 4和25 OR 4和20.结果应该是3但不是3或30使用以下查询:

select product_id 
from product_tag_mapping
where tag_id in ('4','19') or tag_id in (4,29) or tag_id in (4,20)
group by product_id
having count(distinct(tag_id)) >= 2

任何人都可以帮助我,我做错了什么?

我也尝试了其他解决方案,它给了我正确的结果,因为product_id' 3'但查询非常大,这对于大型数据库来说很难:

SELECT DISTINCT product_id 
FROM product_tag_mapping AS t
WHERE EXISTS
  ( SELECT *
    FROM product_tag_mapping AS t1
    WHERE t1.product_id = t.product_id
      AND t1.tag_id = 4
  )
AND EXISTS
  ( SELECT *
    FROM product_tag_mapping AS t2
    WHERE t2.product_id = t.product_id
      AND t2.tag_id = 19
  )
OR EXISTS
  ( SELECT *
    FROM product_tag_mapping AS t2
    WHERE t2.product_id = t.product_id
      AND t2.tag_id = 4
  )
  AND EXISTS
  ( SELECT *
    FROM product_tag_mapping AS t2
    WHERE t2.product_id = t.product_id
      AND t2.tag_id = 20
  )

   OR EXISTS
  ( SELECT *
    FROM product_tag_mapping AS t2
    WHERE t2.product_id = t.product_id
      AND t2.tag_id = 4
  )
  AND EXISTS
  ( SELECT *
    FROM product_tag_mapping AS t2
    WHERE t2.product_id = t.product_id
      AND t2.tag_id = 29
  )

感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

一种捷径方法是将having子句中的条件和用作

select 
product_id from product_tag_mapping 
group by product_id 
having 
( sum(tag_id=4)= 1 and sum(tag_id=19)=1 ) 
or ( sum(tag_id=4)= 1 and sum(tag_id=29)=1 ) 
or ( sum(tag_id=4)= 1 and sum(tag_id=20)=1 ) ;

如果产品出现多次相同的tag_id,您可以使用>= 1代替=1

答案 1 :(得分:0)

SELECT product_id,GROUP_CONCAT(tag_id SEPARATOR ',') AS tag_list
FROM product_tag_mapping GROUP BY product_id HAVING (
FIND_IN_SET( 4, tag_list ) AND FIND_IN_SET( 19, tag_list ))
OR (FIND_IN_SET( 4, tag_list ) AND FIND_IN_SET( 20, tag_list ))
OR (FIND_IN_SET( 4, tag_list ) AND FIND_IN_SET( 29, tag_list ))