2016-03-04 65 views
0

我有一個cs cart數據庫,我試圖選擇所有產品的所有屬性,問題是對於產品的每個單獨屬性,我的查詢創建一個新的行,我想爲每個產品擁有一行,並將所有屬性分爲列。SQL:將具有相同ID的行拆分爲列+左連接

這是我的查詢現在:

SELECT a.product_id, b.variant, c.description, d.product_code 
FROM cscart_product_features_values a 
LEFT JOIN cscart_product_feature_variant_descriptions b ON a.variant_id = b.variant_id 
LEFT JOIN cscart_product_features_descriptions c ON a.feature_id = c.feature_id 
LEFT JOIN cscart_products d ON a.product_id = d.product_id 

我運行查詢後,我得到以下結果:

product_id;"variant";"description";"product_code" 
38;"1st";"Grade Level";"750" 
38;"Math";"Subject Area";"750" 
38;"Evan-Moor";"Publisher";"750" 
etc next product 

我想是這樣的:

product_id;"product_code";"Grade Level";"Subject Area";"Publisher" 
38;"750";"1st";"Math";"Evan-Moor" 
etc next product 

我們只有3種屬性:成績等級,學科領域和出版商。

任何想法如何提高我的查詢和實現?即使連接了由「,」分隔的一列中的所有3個屬性,我也會很高興。

+0

搜索'PIVOT' –

回答

1

這是一個使用GROUP BY和MAX(case表達式)實現3行到3行的單行轉換的通用SQL解決方案。

SELECT 
     v.product_id 
     , p.product_code 
     , MAX(CASE WHEN fd.description = 'Grade Level' THEN vd.variant END) AS GradeLevel 
     , MAX(CASE WHEN fd.description = 'Subject Area' THEN vd.variant END) AS SubjectArea 
     , MAX(CASE WHEN fd.description = 'Publisher' THEN vd.variant END) AS Publisher 
FROM cscart_products p 
     LEFT JOIN cscart_product_features_values v ON p.product_id = v.product_id 
     LEFT JOIN cscart_product_feature_variant_descriptions vd ON v.variant_id = vd.variant_id 
     LEFT JOIN cscart_product_features_descriptions fd ON v.feature_id = fd.feature_id 
GROUP BY 
     v.product_id 
     , p.product_code 

這種方法應該適用於任何SQL數據庫。

請注意,我已經改變了表的順序,因爲我認爲cscart_products中必須有一行,但其他表中可能沒有相關的行。

我也改變了別名,我個人不關心基於查詢中使用順序的別名(例如,我只是改變了順序,所以我不得不改變所有的引用)。我使用'p'=產品,'v'=變體,'vd'=變體描述&'fd'=特徵描述' - 用這種約定替換別名,我可以在不改變每個參考的情況下重新排列查詢。

+0

謝謝,作品完美,也爲解釋! – Speedwheelftw

相關問題