14

我有两个具有这种结构的表

categories
--------------------------------
id  | create
1   | 2012-12-01 12:00:00
2   | 2012-12-01 12:00:00

category_i18ns
--------------------------------
category_id     | lang  | title
1               | en    | home page
1               | de    | HomE PAGEa
1               | fa    | خانه
2               | en    | about

一些类别具有所有语言数据,而另一些类别具有所有语言数据。例如类别 id 2 刚刚en翻译了标题。我想要一个查询,首先检查当前语言以获取检索标题,然后如果不存在则显示另一个。

我有一个查询来使用 i18n 数据获取当前类别数据,在这个当前示例de中是默认语言。对于类别 ID 1,我们有de标题,但对于类别2我们没有。所以我想要英文版作为类别的标题

SELECT * FROM `mhf_swe_ndzhmju3_test`.`categories` AS `Category`
LEFT JOIN `mhf_swe_ndzhmju3_test`.`category_i18ns` AS `CategoryLocale` ON (
`CategoryLocale`.`category_id` = `Category`.`id`
AND `CategoryLocale`.`lang` = 'de')

对“de”语言的渴望

Category.id     CategoryLocale.title    CategoryLocale.lang
1               HomE PAGEa              de
2               about                   en
4

3 回答 3

20
SELECT Category.id,
        COALESCE(a.lang, b.lang) lang,
        COALESCE(a.title, b.title) title
FROM   categories AS Category
      LEFT JOIN category_i18ns AS a
           ON a.category_id = Category.id AND a.lang = 'de'
      LEFT JOIN category_i18ns AS b
           ON b.category_id = Category.id AND b.lang = 'en'
于 2012-12-11T09:59:52.077 回答
3

如果您有优先顺序,请左加入所有语言并按优先顺序将它们合并:

SELECT Category.id,
    COALESCE(a.lang, b.lang, c.lang, d.lang) lang,
    COALESCE(a.title, b.title, c.title, d.title) title
FROM   categories AS Category
  LEFT JOIN category_i18ns AS a
       ON a.category_id = Category.id AND a.lang = 'de'
  LEFT JOIN category_i18ns AS b
       ON b.category_id = Category.id AND b.lang = 'en'
  LEFT JOIN category_i18ns AS c
       ON c.category_id = Category.id AND c.lang = 'fr'
  LEFT JOIN category_i18ns AS d
       ON d.category_id = Category.id AND d.lang = 'es';

如果您想从随机语言中获取文本,请使用以下查询:

SELECT Category.id,
        COALESCE(a.lang, b.lang) lang,
        COALESCE(a.title, b.title) title
FROM   categories AS Category
      LEFT JOIN category_i18ns AS a
           ON a.category_id = Category.id AND a.lang = 'de'
      LEFT JOIN category_i18ns AS b
           ON b.category_id = Category.id
GROUP BY Category.id

http://sqlfiddle.com/#!2/2beaf/5

于 2012-12-11T10:36:46.697 回答
1

好的,这不是最好的解决方案,但我认为应该可以正常工作:

SELECT * FROM categories c INNER JOIN category_i18ns t1 
ON c.id = t1.category_id AND t1.lang = 'de'

UNION 

SELECT * FROM categories c LEFT JOIN category_i18ns t2 
ON c.id = t2.category_id and t2.lang != 'de' 
WHERE t2.category_id not in
   (SELECT DISTINCT category_id FROM category_i18ns WHERE lang = 'de') 
GROUP BY c.id

SQL 小提琴示例

于 2012-12-11T10:34:52.417 回答