mysql group_concat有条件

时间:2011-02-13 00:57:40

标签: mysql group-concat

我认为这种情况很少见,不确定是否可以使用。

我有这个问题:

$sql = "SELECT id_product,GROUP_CONCAT(id_tag  ORDER BY id_tag  ) AS producto  
FROM ps_product_tag  
where id_product = '194'
GROUP BY id_product";

我得到了这个结果:

Array ( [id_product] => 194 [producto] => 36,190,273,274,275,276,277,278,279,280,281,282,284,286,287,289 ) 

我需要的是做一些过滤id_tag结果数组的多个where条件。

WHERE t.`id_tag` = '275'
AND t.`id_tag` = '282'
AND t.`id_tag` = '286'
AND t.`id_tag` = '289'

但我无法做到。

任何人都可以帮助我。

3 个答案:

答案 0 :(得分:3)

您可以像这样添加HAVING子句:

SELECT
    id_product,
    GROUP_CONCAT(id_tag ORDER BY id_tag) AS producto,
    COUNT(*) as `n`
FROM ps_product_tag
WHERE id_tag IN ('275', '282', '286', '287')
GROUP BY id_product
HAVING `n`=4

答案 1 :(得分:1)

假设(id_product, id_tag)是唯一的,请尝试:

SELECT id_product
FROM ps_product_tag
WHERE id_tag IN ('275', '282', '286', '287')
GROUP BY id_product
HAVING COUNT(id_tag) = 4

答案 2 :(得分:1)

如果您需要带有四个标签的产品,您可以使用:

SELECT
      p.id_product,
      GROUP_CONCAT(p.id_tag ORDER BY id_tag) AS producto,
  FROM ps_product_tag as p INNER JOIN 
   (SELECT id_product  
      FROM ps_product_tag
      WHERE id_tag IN ('275', '282', '286', '287')
    GROUP BY id_product HAVING COUNT(*) = 4) as alltags
    ON alltags.id_product = p.id_product
GROUP BY id_product