我尝试按 parent_id 和语言从表中选择所有行“标签”。默认语言为 en。
list = SELECT * FROM labels WHERE parent_id = x AND lang='de'
if( list.isEmpty() ){
list = SELECT * FROM labels WHERE parent_id = x AND lang='en'
}
如何只使用一个 MySQL 语句来处理这个问题?
非常感谢
我尝试按 parent_id 和语言从表中选择所有行“标签”。默认语言为 en。
list = SELECT * FROM labels WHERE parent_id = x AND lang='de'
if( list.isEmpty() ){
list = SELECT * FROM labels WHERE parent_id = x AND lang='en'
}
如何只使用一个 MySQL 语句来处理这个问题?
非常感谢
使用where not exists
和union all
:
SELECT * FROM labels WHERE parent_id = x AND lang='de'
union all
SELECT *
FROM labels
WHERE parent_id = x AND lang = 'en' and
not exists (SELECT * FROM labels WHERE parent_id = x AND lang='de')
试试这个,
SELECT *
FROM labels
WHERE parent_id = x AND
lang =
(
SELECT lang
FROM labels
WHERE parent_id = x
ORDER BY FIELD(lang, 'en', 'de') DESC
LIMIT 1
)
FIELD()函数返回列表中字符串的索引。
这里使用JOIN
SELECT DISTINCT a.*
FROM labels a
INNER JOIN
(
SELECT parent_id, lang
FROM labels
WHERE parent_id = 1
ORDER BY FIELD(lang, 'en', 'de') DESC
LIMIT 1
) b ON a.parent_id = b.parent_id AND
a.lang = b.lang
WHERE a.parent_id = 1