简体   繁体   中英

Filter one category of a product, but bring all categories of the filtered products

Here's the thing.

I have a query that brings all products that I have in my database. Those products are of one or more categories. So I have 3 tables.
- Product table
- Category table
- Table that holds the relations between those two.

I use GROUP_CONCAT to get the names of all categories from which a product belongs when getting the products and it works fine. I get the results I expect.

The problem lies when I filter for one category. Then the GROUP_CONCAT no longer works, it brings only products from the desired category but not ALL the categories from which that product belongs.

Here's the query when I'm not filtering for a specific category.

SELECT p.*, GROUP_CONCAT( c.title SEPARATOR ', ') as category
FROM products p
INNER JOIN products_categories_relation pcr ON pcr.product_id = p.id
INNER JOIN categories c ON pcr.category_id = c.id
WHERE p.status = 1
GROUP BY p.id
ORDER BY p.name ASC
LIMIT 16
OFFSET 0

And here's the query when I filter for a specific category:

SELECT p.*, GROUP_CONCAT( c.title SEPARATOR ', ') as categories
FROM product p
INNER JOIN products_categories_relation pcr ON pcr.product_id = p.id
INNER JOIN categories c ON pcr.category_id = c.id
WHERE p.status = 1
AND pcr.category_id = 27 
GROUP BY p.id
ORDER BY p.name ASC
LIMIT 16
OFFSET 0

Can someone help me out?

You can try this

SELECT p.*, GROUP_CONCAT( c.title SEPARATOR ', ') as categories
FROM product p
INNER JOIN products_categories_relation pcr ON pcr.product_id = p.id
INNER JOIN categories c ON pcr.category_id = c.id
WHERE p.status = 1
AND exists( select * from products_categories_relation where products_categories_relation.category_id = 27 and products_categories_relation.product_id = p.id )
GROUP BY p.id
ORDER BY p.name ASC
LIMIT 16
OFFSET 0

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