我使用多语言支持的数据库。但我不知道如何根据语言查询数据库中的翻译文本。
这是我的桌子DDL。如果您有任何疑问,请询问我。
类别表
CREATE TABLE IF NOT EXISTS `catalog_category` (
`id` int(10) unsigned NOT NULL,
`name_translation_id` int(10) unsigned NOT NULL,
`description_translation_id` int(10) unsigned NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
语言表
CREATE TABLE IF NOT EXISTS `languages` (
`id` int(10) unsigned NOT NULL,
`language_name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`language_code` varchar(2) COLLATE utf8_unicode_ci NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
语言翻译表
CREATE TABLE IF NOT EXISTS `language_translation` (
`id` int(10) unsigned NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
语言翻译条目表
CREATE TABLE IF NOT EXISTS `language_translation_entry` (
`id` int(10) unsigned NOT NULL,
`translation_id` int(10) unsigned NOT NULL,
`language_id` int(10) unsigned NOT NULL,
`translation_text` text COLLATE utf8_unicode_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
目前我正在使用此查询来获取结果,但它仅从名称中获取。我也希望在结果中进行描述。
SELECT lte.translation_text as name FROM catalog_category AS cc
LEFT JOIN language_translation lt ON lt.id = cc.name_translation_id
LEFT JOIN language_translation_entry AS lte ON lte.translation_id = lt.id
LEFT JOIN languages AS l on l.id = lte.language_id
WHERE l.language_code = "en"
我需要根据单个查询中的语言代码从翻译条目表中获取类别名称和描述的翻译文本。
答案 0 :(得分:1)
您可以使用子选择:
SELECT
(select lte.translation_text
from language_translation_entry AS lte
JOIN languages AS l on l.id = lte.language_id
WHERE lte.translation_id = cc.name_translation_id
and l.language_code = "en"
) as name,
(select lte.translation_text
from language_translation_entry AS lte
JOIN languages AS l on l.id = lte.language_id
WHERE lte.translation_id = cc.description_translation_id
and l.language_code = "en"
) as description
from catalog_category AS cc
这假设每个(translation_id, laguage_id)
有最多1个条目,否则会出错,因为这些子选择只能返回一个值。
我遗漏了表格language_translation
,因为您可能只使用它来获取自动增量值,而不是连接所必需的。
另一种方法是为您需要翻译的每个列使用另一个join
,例如,使用
SELECT lte.translation_text as name,
lt2.translation_text as description,
FROM catalog_category AS cc
LEFT JOIN language_translation_entry AS lte
ON lte.translation_id = cc.name_translation_id
LEFT JOIN languages AS l on l.id = lte.language_id
LEFT JOIN language_translation_entry AS lte2
ON lte2.translation_id = cc.name_translation_id
and lte2.language_id = l.id
WHERE l.language_code = "en"
我假设您希望两种翻译都是同一种语言。
顺便说一下,left join
实际上就像普通的join
一样,因为你使用where l.language_code = "en"
,它必须存在。如果你想要一个真实的left join
,你必须将这个条件移到on
- 子句,因此它可能会丢失(如果你的翻译有可能丢失,你仍然希望得到一个查询结果)。对于description
,已经允许丢失以使代码更短,否则您必须将条件从on
移动到where
子句,因此将最后一部分更改为< / p>
LEFT JOIN language_translation_entry AS lte2
ON lte2.translation_id = cc.name_translation_id
WHERE l.language_code = "en" and lte2.language_id = l.language_id