我正在为库存管理应用程序构建数据库,我必须维护具有多个类别层次结构的产品。我有以下数据库模型:
我想检索产品、描述、计量单位和类别,为此我使用了以下查询:
SELECT P.ID
,P.wrin
,P.description AS productDescription
,CT.pdtCat AS productCategory
,CONCAT(UN.description,' - ',UN2.description,' - ',UN3.description) AS unitDecomposition
FROM product P
-- JOIN to product_category table
JOIN (
SELECT PC3.ID as catID
,CONCAT(PC1.category,' - ',PC2.category,' - ',PC3.category) as pdtCat
FROM product_category AS PC1
LEFT JOIN product_category AS PC2 ON PC2.parentid = PC1.id
LEFT JOIN product_category AS PC3 ON PC3.parentid = PC2.id
WHERE PC1.parentid IS NULL
) CT ON CT.catID = P.categoryId
JOIN unit UN ON P.primaryUOM = UN.ID
JOIN unit UN2 ON P.secondaryUOM = UN2.ID
JOIN unit UN3 ON P.tertiaryUOM = UN3.ID
这个查询的输出是:
最佳答案
在您的子选择中,您将从“顶部”类别加入底部类别并选择底部类别的 ID。如果没有 3 级类别,则没有结果。
尝试这样的事情:
SELECT P.ID
,P.wrin
,P.description AS productDescription
,CT.pdtCat AS productCategory
,CONCAT(UN.description,' - ',UN2.description,' - ',UN3.description) AS unitDecomposition
FROM product P
-- JOIN to product_category table
JOIN (
SELECT PC3.ID as catID
,CONCAT(PC1.category,' - ',COALESCE(PC2.category, ''),' - ',COALESCE(PC3.category, '')) as pdtCat
FROM product_category AS PC3
LEFT JOIN product_category AS PC2 ON PC3.parentid = PC2.id
LEFT JOIN product_category AS PC1 ON PC2.parentid= PC1.id
) CT ON CT.catID = P.categoryId
JOIN unit UN ON P.primaryUOM = UN.ID
JOIN unit UN2 ON P.secondaryUOM = UN2.ID
JOIN unit UN3 ON P.tertiaryUOM = UN3.ID
编辑: 我的查询将为产品类别生成一些“- - 类别”结果。 由于我的强项是 MSSQL,所以这是一个让你看起来更漂亮的练习 ;)
关于Mysql join 多表分层数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46445611/