我有以下两张表:
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中创建一个查询,在该查询中,如果翻译表中有一个已定义的title,则选择所有characteristics并将其连接到characteristics_translations。如果没有,则应该从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'发布于 2016-02-18 14:08:09
使用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; 发布于 2016-02-18 14:07:28
试试聚结
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;它将从给定的参数列表返回第一个非空值。
https://stackoverflow.com/questions/35483499
复制相似问题