复杂的MySQL加入替换列

时间:2011-11-08 19:45:38

标签: php mysql join

包含内容信息的表格 - content

+----------+-------------+-------------------+--------------------------------+
| (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.title替换为translations.value并将其替换为描述(不同组件(content)表的更多/更少数据) content.titletranslations.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'

我如何实现这一目标?

提前致谢!

1 个答案:

答案 0 :(得分: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列的别名。