同一查询中的多个SELECT会覆盖彼此的结果

时间:2014-09-30 12:16:23

标签: mysql mariadb

对于令人困惑的标题感到抱歉,最好直接查看代码:

样本表:

|     key    |    value  |    MainLanguage     |     SubLanguage     |
|    mLangID |      5    |       default       |         en          |
|    mLangID |      3    |         esES        |         en          |
|    mTitle  |  Title    |       default       |         en          |
|    mTitle  |  Título   |         esES        |         es          |

我想避免使用这些查询:

SELECT * FROM translation.strings WHERE MainLanguage = 'esES' AND lang='es'
SELECT * FROM translation.strings WHERE MainLanguage = 'esES' AND lang='en'
SELECT * FROM translation.strings WHERE MainLanguage = 'default' AND lang='en'
...

并将它们组合成一个,但要确保第一个查询的结果不会被第二个查询的结果覆盖,依此类推。或者,如果它更容易,反之(第二个查询覆盖第一个查询的结果,第三个覆盖第二个查询等)

2 个答案:

答案 0 :(得分:0)

使用UNION ALL组合结果,这不会删除重复的行。

答案 1 :(得分:0)

如果我理解正确,您希望union allwhere子句来优先考虑结果。我猜你想要每key行一行。如果是这样,这可能会起作用

SELECT *
FROM translation.strings s
WHERE MainLanguage = 'esES' AND lang = 'es'
UNION ALL
SELECT *
FROM translation.strings s
WHERE MainLanguage = 'esES' AND lang = 'en' AND
      NOT EXISTS (select 1
                  from translation.strings s2
                  where s2.key = s.key and s2.MainLanguage = 'esES' AND s2.lang = 'es'
                 )
UNION ALL
SELECT *
FROM translation.strings s
WHERE MainLanguage = 'default' AND lang = 'en' AND
      NOT EXISTS (select 1
                  from translation.strings s2
                  where s2.key = s.key and
                        (s2.MainLanguage = 'esES' AND s2.lang = 'es' or
                         s2.MainLanguage = 'esES' AND s2.lang='en'
                        )
                 );

注意:在其他数据库中有更简单的方法可以解决这个问题。