我有3个表,产品,类别和couple_product_category 我希望数据库中的所有产品都包含一系列耦合类别。 但是,当我添加一个尚未与类别相关联的新产品时,这种方式可以正常工作。
我想要最快的方法来阻止性能。 这就是我现在所拥有的:
SELECT
product.id,
product.product_name,
GROUP_CONCAT(productcategory.name SEPARATOR '; ') AS categories
FROM
m_catalog_products AS product
LEFT JOIN
couple_product_category AS category
ON
category.product_id = product.id
INNER JOIN
m_catalog_productcategoy AS productcategory
ON
productcategory.id = category.category_id
GROUP BY
product.id
ORDER BY product.id, product.is_active ASC
这将导致类似:
ID Name Categories
-- --------- ----------------------
1 Product A Category A; Category B
2 Product B Category C
但是,如果产品C尚未与任何类别相关联,则应显示如下:
ID Name Categories
-- --------- ----------------------
1 Product A Category A; Category B
2 Product B Category C
3 Product C
答案 0 :(得分:1)
LEFT JOIN m_catalog_productcategoy
代替INNER JOIN
:
SELECT
p.id,
p.product_name,
GROUP_CONCAT(pc.name SEPARATOR '; ') AS categories
FROM m_catalog_products AS p
LEFT JOIN couple_product_category AS c ON c.product_id = p.id
LEFT JOIN m_catalog_productcategoy AS pc ON pc.id = c.category_id
GROUP BY p.id
ORDER BY p.id, p.is_active ASC;