2017-09-27 14 views
1

私は在庫管理アプリケーション用のデータベースを構築しており、カテゴリの複数の階層を持つ製品を管理する必要があります。私は、次のデータベースモデルを持っている: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

"トップ"カテゴリからボトムカテゴリに参加し、下位の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 

EDIT: - 製品カテゴリの結果 'のカテゴリ - ' 私のクエリは、いくつかを生成します

はこのような何かを試してみてください。 私の強みがMSSQLにあるという事実のために、それはもっと見栄えの良い練習です;)

+0

あなたは何かを追加するのを忘れましたか? ^^元のクエリと同じようです... –

+0

いいえ、私はサブ選択で結合順序を変更しました。 –

+0

カテゴリのレベルが1つしかない製品にはnull値を返します。/ –

関連する問題