我正在为库存管理应用程序构建数据库,我必须维护具有多个类别层次结构的产品。我有以下数据库模型:
我想检索我使用过以下查询的产品,说明,度量单位和类别:
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
此查询的输出为:
答案 0 :(得分:1)
在您的子选择中,您将加入" top"类别到底部类别并选择底部类别的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中,这是一个让你看起来更漂亮的练习;)