2016-11-16 57 views
-1

我有3個表,Products,LanguagesProducts_translation帶動態返回列名的mysql查詢

如何在一個查詢中同時檢索一個產品和所有翻譯?

我有這個

SELECT p.*, pt.description FROM Products p 
LEFT JOIN Products_translation pt ON p.id=pt.product_id 
LEFT JOIN Languages l ON pt.language =l.code 

我有3種語言,但它只能獲取一個字段名稱「描述」,我想它返回3(語言的數量),喜歡的東西description_en, description_es, description_fr

可以製作類似pt.description AS 'description'+'l.code'的東西嗎?

+3

請分享表格結構 – VishalChaturvedi

+0

我已經添加了他們 – F79

回答

2

這是一個非常常見的問題,我相當肯定它已被多次回答(例如:Mysql: joining tables for translation records)。無論如何,如果你只有3種語言,只是這樣做:

SELECT p.*, pt_en.description as description_en, pt_es.description as description_es, pt_fr.description as description_fr FROM Products p 
LEFT JOIN Products_translation pt_en ON (p.id=pt.product_id and pt.language = 'en') 
LEFT JOIN Products_translation pt_es ON (p.id=pt.product_id and pt.language = 'es') 
LEFT JOIN Products_translation pt_fr ON (p.id=pt.product_id and pt.language = 'fr') 

如果有3個以上,或不同數量,搜索旋轉透視表獲取更多信息。在SQL中做這件事並不容易,所以通常選擇產品會更快,在單獨的查詢中選擇這些產品的所有翻譯,並在數據庫之外構建所需的結果。

+0

謝謝,但我想要的只是在不知道語言值 – F79