mysql与条件连接

时间:2012-12-11 09:44:26

标签: mysql sql join conditional-statements

我有两个这种结构的表

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

3 个答案:

答案 0 :(得分:15)

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'

答案 1 :(得分:2)

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

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

答案 2 :(得分: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 Fiddle Example