Mysql join 多表分层数据

标签 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 级类别,则它似乎会偏离方向。该产品未出现在结果中。请帮助:)

最佳答案

在您的子选择中,您将从“顶部”类别加入底部类别并选择底部类别的 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/

相关文章:

php - 如果一行中有多个id存储,则连接多个表

php - 从我有特定 id 的 mysql JSON 数据类型中选择不同的值

php - 具有挑战性的 SQL 查询

mysql - 在 MySQL 中对 2 个表进行分组而不进行连接

php mysql 非平凡表是什么意思?

mysql - 增加 Windows Azure 网站上 ClearDB MySQL 的 max_user_connections

java - 使用 Spring 时数据未发送到 MySQL 数据库

用于分页的 php 示例脚本

php - CLI 无法访问 getenv

mysql - 触发错误 : SQL Error (1193): Unknown system variable 'Showedup'