使用FIND_IN_SET和GROUP_CONCAT时的MySQL查询加入问题

时间:2019-01-14 20:53:29

标签: mysql sql join left-join find-in-set

因此,我有一个产品/类别/品牌结构,其中产品类别由包含以逗号分隔的类别ID列表(即101,105,108)的列以及品牌ID列标识。

我正在尝试获取所有产品的列表,用逗号分隔的类别名称和品牌名称列表替换类别ID。

我有以下有效的查询:

SELECT 
    productid AS product_id,
    prodname AS name,
    prodcode AS code,
    proddesc AS description,
    prodprice AS price,
    GROUP_CONCAT(c.catname)
FROM
    products p,
    categories c
WHERE
    FIND_IN_SET(c.categoryid, p.prodcatids)
GROUP BY p.productid

但是,当我尝试按如下方法离开并获得品牌名称时,它会中断并显示p.prodbrandid列不存在(确实存在)。

SELECT 
    productid AS product_id,
    prodname AS name,
    prodcode AS code,
    proddesc AS description,
    prodprice AS price,
    b.brandname AS brand,
    GROUP_CONCAT(c.catname)
FROM
    products p,
    categories c
        LEFT JOIN
    brands b ON p.prodbrandid = b.brandid
WHERE
    FIND_IN_SET(c.categoryid, p.prodcatids)
GROUP BY p.productid

任何指向我所缺少内容的指针将不胜感激!

1 个答案:

答案 0 :(得分:3)

根据评论中的建议:

SELECT 
    p.productid AS product_id,
    p.prodname AS name,
    p.prodcode AS code,
    p.proddesc AS description,
    p.prodprice AS price,
    b.brandname AS brand,
    GROUP_CONCAT(c.catname)
FROM
    products p
    INNER JOIN categories c on FIND_IN_SET(c.categoryid, p.prodcatids) > 0
    LEFT JOIN brands b ON p.prodbrandid = b.brandid        
GROUP BY p.productid

不过,将数据存储为逗号分隔的列表并不理想;确实应该将其拆分为一个附加表,该表将产品与类别之间的many:many关系(多个产品可以具有多个类别)分解为两个1:many关系(productcategories表,具有productid,categoryid对)< / p>

一次性考虑这样的事情:

CREATE TABLE ProductCategories(ProductId INT, CategoryId INT)

INSERT INTO ProductCategories
  SELECT 
  p.productid, c.categoryid
FROM
  products p
  INNER JOIN categories c on FIND_IN_SET(c.categoryid, p.prodcatids) > 0

然后继续使用它,并删除类别列