我只想向GROUP BY
提供一个SQL语句,但是如果该行可用,我希望它尝试选择一行。
例如,我有这样的陈述:
SELECT *
FROM `translations`
WHERE `lang` = "pl" OR `lang` = "en"
GROUP BY `key`
在此声明中,我尝试选择lang
为pl
的所有位置,并且只有在等效en
没有结果时才会获得pl
结果行。
key
是多个lang
的列。
如果我运行上述语句,那么所有结果都将是lang
en
的结果,我理解为什么这不是我想要的行为,我不确定如何调整它。
我知道如何以编程方式执行此操作,但是我认为它只适用于SQL。
答案 0 :(得分:1)
您可以将其标记为union all
语句。我的假设是key
,lang
对唯一标识一行(否则您仍然可以执行group by
以获得每行一行)。
我们的想法是选择lang = 'pl'
的所有行。然后为同一个键选择lang = 'en'
与'pl'
没有对应行的行:
SELECT *
FROM translations
WHERE lang = 'pl'
union all
SELECT *
FROM translations
WHERE lang = 'en' and
`key` not in (select `key` from translations where lang = 'pl')
答案 1 :(得分:0)
不是最佳的,但它应该给出所需的结果:
SELECT a.*
FROM
(
SELECT * FROM `translations` where `lang` = "pl"
UNION ALL
SELECT * FROM `translations` a where `lang` = "en"
WHERE NOT EXISTS (SELECT NULL FROM `translations` b WHERE b.lang="pl")
)a GROUP BY `key`
答案 2 :(得分:0)
我会这样做:
SELECT COALESCE(`translation_foreign`.`value`, `translations`.`value`) AS `value`
FROM `translations`
LEFT JOIN `translation` as `translations_foreign` ON
translations_foreign.key = translations.key AND
translations_foreign.lang = "pl"
WHERE lang = "en"
GROUP BY `translations`.`key`