Mysql使用分层数据连接多个表

时间:2017-09-27 10:32:10

标签: mysql

我正在为库存管理应用程序构建数据库,我必须维护具有多个类别层次结构的产品。我有以下数据库模型:

enter image description here

我想检索我使用过以下查询的产品,说明,度量单位和类别:

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

此查询的输出为:

enter image description here 我的查询给出了预期的结果,但如果我的产品没有3个级别的类别,我似乎会侧身。该产品未出现在结果中。请帮忙:)

1 个答案:

答案 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中,这是一个让你看起来更漂亮的练习;)