如果在转换表中找不到记录,请选择列

时间:2016-02-18 13:59:38

标签: mysql join

我有以下两张表:
characteristics

╔════╤═══════╗
║ id │ value ║
╠════╪═══════╣
║ 1  │ A     ║
╟────┼───────╢
║ 2  │ B     ║
╟────┼───────╢
║ 3  │       ║
╟────┼───────╢
║ 4  │ X     ║
╚════╧═══════╝

characteristics_translations

╔════╤════════════════════╤══════════╤══════════════╗
║ id │ characteristics_id │ language │ title        ║
╠════╪════════════════════╪══════════╪══════════════╣
║ 1  │ 3                  │ en       │ EN - Cookies ║
╟────┼────────────────────┼──────────┼──────────────╢
║ 2  │ 3                  │ fr       │ FR - Cookies ║
╟────┼────────────────────┼──────────┼──────────────╢
║ 3  │ 3                  │ de       │ DE - Cookies ║
╟────┼────────────────────┼──────────┼──────────────╢
║ 4  │ 4                  │ en       │ EN - Apples  ║
╟────┼────────────────────┼──────────┼──────────────╢
║ 5  │ 4                  │ fr       │ FR - Apples  ║
╚════╧════════════════════╧══════════╧══════════════╝

我正在尝试在MySQL中创建一个查询,如果翻译表中有一个已定义的characteristics,我会在characteristics_translations左边选择所有title。 。如果没有,则应从value选择列characteristics

这是我迄今为止所尝试过的:

SELECT c.id, 
       [c.value OR ct.title] 
FROM   `characteristics` c 
       LEFT JOIN `characteristics_translations` ct 
              ON c.id = ct.characteristics_id 
WHERE  ct.language = 'de' 
        OR ct.language = NULL; 

输出应该是这样的:

{
  "0":{
    id: "1",
    title: "A"
  },
  "1":{
    id: "2",
    title: "B"
  },
  "2":{
    id: "3",
    title: "DE - Cookies"
  },
  "3":{
    id: "4",
    title: "X"
  },
}

最终解决方案

SELECT c.id, COALESCE(ct.title, c.value) title 
FROM   `characteristics` c 
       LEFT JOIN `characteristics_translations` ct 
              ON c.id = ct.characteristics_id 
              AND ct.language = 'de'

2 个答案:

答案 0 :(得分:1)

尝试COALESCE

SELECT c.id, COALESCE(ct.title, c.value) 
FROM   `characteristics` c 
       LEFT JOIN `characteristics_translations` ct 
              ON c.id = ct.characteristics_id 
WHERE  ct.language = 'de' 
        OR ct.language = NULL;

它将从给定的参数列表中返回第一个非空值。

答案 1 :(得分:1)

使用coalesce()从参数列表中获取第一个非空值:

SELECT c.id, 
       coalesce(ct.title, c.value) as title
FROM   `characteristics` c 
       LEFT JOIN `characteristics_translations` ct 
              ON c.id = ct.characteristics_id 
WHERE  ct.language = 'de' 
        OR ct.language = NULL;