首页 > 解决方案 > 根据条件选择不同的结果

问题描述

我有以下查询:

select a,b,c,firstConditionKey,secondConditionkey from 
(select ..... - big query - ..... ) as main;

我需要的是从查询中返回单行,因此如果firstConditionKey不为空,则该行会像这样,min(firstConditionKey)因为我不在乎它是哪一行,只要它是具有 的行firstConditionKey,否则,如果有没有带有firstconditionKey的行,从有 a 的行中返回一行,secondConditionKey如果没有,则返回任何行。

a   b   c   firstConditionKey   secondConditionKey
x   x   x          1                    1
x   x   x          2                    2
x   x   x                               2

a   b   c   firstConditionKey   secondConditionKey
x   x   x                                
x   x   x                               2
x   x   x                               2

所以在第一种情况下,我会返回第一行。在第二种情况下,我将返回第二行。

基本上,如果存在带有 的行firstConditionKey,则返回找到的第一行,否则,返回带有 的第一行secondConditionKey

标签: mysqlsqlselectcase

解决方案


如果你想要一行,你可以使用order byand limit。所以,基本思路是:

select a, b, c, firstConditionKey, secondConditionkey
from (select ..... - big query - ..... ) main
order by (firstConditionKey is not null) desc,
         (secondConditionKey is not null) desc
limit 1;

如果两个键都是 ,这并不能解决最后一个不返回行的条件NULL,所以让我们将其表述为:

select a, b, c, firstConditionKey, secondConditionkey
from (select ..... - big query - ..... ) main
where firstConditionKey is not null or secondConditionKey is not null
order by (firstConditionKey is not null) desc,
         (secondConditionKey is not null) desc
limit 1;

推荐阅读