i have this database setup:
products
tags
product_tag
If have this records in my database
How do i query to get the products that have tag_id 1 AND 2 (it must by products with tag_id 1 AND 2) in this example: "Product A" and "Product C"
SELECT *
FROM products
WHERE id IN (
SELECT product_id
FROM product_tag
GROUP BY product_id
HAVING GROUP_CONCAT(tag_id) = '1,2'
)
Use this
SELECT P.id
FROM products P
INNER JOIN products_tags PT ON PT.product_id = P.id
WHERE PT.tag_id IN (1,2)
GROUP BY P.id
HAVING COUNT(PT.*) = 2
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.