[英]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.
所以我有3张桌子。
- 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. 获取产品时,我使用GROUP_CONCAT获取产品所属的所有类别的名称,并且效果很好。 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.
然后,GROUP_CONCAT不再起作用,它仅带来所需类别的产品,而不带来该产品所属的所有类别。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.