我想选择给定语言的产品翻译,但也包括翻译不存在时的后备。这是数据集:
+----+------------+---------------+-----------------+
| id | product_id | language_code | name |
+----+------------+---------------+-----------------+
| 1 | 1 | en | Name in english |
| 2 | 1 | fr | Name in french |
| 3 | 1 | es | Name in spanish |
| 4 | 2 | en | Another product |
+----+------------+---------------+-----------------+
我正在处理一个查询,该查询选择 language_code='fr' 并在 'fr' 不存在时回退到 'en'。结果应该类似于:
+----+------------+---------------+-----------------+
| id | product_id | language_code | name |
+----+------------+---------------+-----------------+
| 2 | 1 | fr | Name in french |
| 4 | 2 | en | Another product |
+----+------------+---------------+-----------------+
我尝试了多种方法:
SELECT translations.id, translations.language_code, translations.name
FROM translations
WHERE language_code = 'fr'
OR language_code = 'en';
这将限制为给定语言,但不会删除重复项 (id=1)。
我见过多种使用 GROUP BY
的解决方案,但我一直遇到 only_full_group_by
问题,而且我不知道如何解决。
SELECT *
FROM translations
WHERE language_code = 'fr'
OR language_code = 'en'
GROUP BY product_id;
最佳答案
您可以使用不存在
和或
:
select t.id, t.language_code, t.name
from translations t
where t.language_code = 'fr' OR
(t.language_code = 'en' and
not exists (select 1 from translations t2 where t2.product_id = t.product_id and t2.language_code = 'fr'
));
关于mysql - 从表中选择一行或另一行,具体取决于其他行是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59145517/