2011-11-08 65 views
0

表保存內容的信息 - content複雜MySQL的加入與替換列

+----------+-------------+-------------------+--------------------------------+ 
| (int) id | (int) title | (int) description | (string) tags     | 
+----------+-------------+-------------------+--------------------------------+ 
|  1 |   12 |    18 | super, awesome, must-see  | 
+-----------------------------------------------------------------------------+ 
|  4 |   25 |    26 | randomness, funny-stuff, cool | 
+-----------------------------------------------------------------------------+ 

表中包含翻譯信息 - translations

+-----------+---------------------------------+----------------+ 
| (int) tid | (text) value     | (varchar) code | 
+-----------+---------------------------------+----------------+ 
|  12 | Super-awesome-mustsee   | en    | 
+--------------------------------------------------------------+ 
|  18 | <here would be the description> | en    | 
+--------------------------------------------------------------+ 
| <more translation data that is not necessary for this xmpl.> | 
+--------------------------------------------------------------+ 

我想實現的是,以取代content.titletranslations.value以及相同的描述(更多/更少數據爲不同組件(content)表)其中content.title匹配translations.tid,如:

+----------+-----------------------+---------------------------------+--------------------------------+ 
| (int) id | (text) title   | (text) description    | (string) tags     | 
+----------+-----------------------+---------------------------------+--------------------------------+ 
|  1 | Super-awesome-mustsee | <here would be the description> | super, awesome, must-see  | 
+-----------------------------------------------------------------------------------------------------+ 

到目前爲止,我必須只能加入翻譯數據爲一個值......是的,聯接所不能替代的。 :|

SELECT `content` . * , `translations`.value 
FROM `content` 
JOIN `translations` ON `translations`.tid = `content`.title 
WHERE `translations`.code = 'en' 

我該如何做到這一點?

在此先感謝!

+0

此線路:JOIN'translations' ON'translations'.tid ='content'.title似乎是錯誤的:您必須加入content.id,而不是標題... – Nanocom

回答

2

沒有那麼複雜:

SELECT 
    `c`.`id`, 
    `tt`.`value` AS title, 
    `td`.`value` AS description, 
    `c`.`tags` 
FROM 
    `content` `c` 
LEFT JOIN 
    `translations` `tt` ON (`tt`.`tid` = `c`.`title` AND `tt`.`code` = 'en') 
LEFT JOIN 
    `translations` `td` ON (`td`.`tid` = `c`.`description` AND `td`.`code` = 'en') 

基本上你需要刪除*和指定精確列和連接表的別名。第二件事是,你必須在同一張桌子上創建雙連接,一個獲得標題翻譯,第二個獲得描述。要在結果中「替換」,只需使用value列的別名即可。

+0

啊,謝謝,就像一個魅力。不知道你可以將ON語句分組。 – jolt