实际上没有必要拥有多张桌子,除非您计划拥有数百万个故事......我通常会使用两张桌子;一个用于item,另一个用于localized item
例如,一个故事会是这样的
表格“故事”
id INTEGER (Primary Key)
creation_date DATE_TIME
author VAR_CHAR(32)
..other general columns..
表格“story_localized”
story_id INTEGER (Foreign Key of story.id) \
lang CHAR(2) -- (Indexed, unique -- story_id+lang)
content TEXT
..other localized columns..
执行查询只需JOINing 两个表即可:
SELECT s.*, sl.*
FROM story s
JOIN story_localized sl ON s.id = sl.story_id
WHERE s.id = 1 -- the story you're looking for here
AND sl.lang = 'en' -- your language here
-- other conditions here
这种配置有几个优点:
- 您的所有数据都在同一个表中,无需同步 CRUD 操作
- 您可以为任何故事添加新语言,而无需创建更多表格
- 等
** 编辑 **
作为奖励,这里有一个“技巧”,可以轻松检索故事,无论它是用什么语言编写的
SELECT *
FROM (SELECT *
FROM story s
JOIN story_localized sl ON s.id = sl.story_id
WHERE s.id = {storyId}
AND sl.lang = {desiredLanguage} -- example : 'es'
UNION
SELECT *
FROM story s
JOIN story_localized sl ON s.id = sl.story_id
WHERE s.id = {storyId}
AND sl.lang = {defaultLanguage} -- example : 'en'
UNION
SELECT *
FROM story s
JOIN story_localized sl ON s.id = sl.story_id
WHERE s.id = {storyId}
LIMIT 1 -- ..get the first language found
) story_l
LIMIT 1 -- only get the first SELECTed row found
将尝试获取{desiredLanguage} 中的故事,如果该故事没有以该语言提供,请尝试以{defaultLanguage}(即网站的默认语言)找到它,如果仍然没有找到,它不会获取故事的语言无关紧要,因此请获取找到的第一个。一站式查询,您只需要 3 个参数:故事 ID、所需语言和默认后备语言。
此外,您可以通过一个简单的查询轻松找到故事的可用语言:
SELECT sl.lang
FROM story_localized sl
WHERE sl.story_id = {storyId}