2011-11-08 34 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