简体   繁体   中英

Mysql group_contact with conditions

I think this is rare and not sure if posiblle.

I have this query:

$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";

And i get this result:

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

What i need is to do make some filter the id_tag resulting array with multiple where conditions.

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

But i'm not able to doit.

Can anyone help me please.

You can add a HAVING clause like this:

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

Assuming that (id_product, id_tag) is unique, try this:

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

If you need the products with the four tags, you can use:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM