根据条件选择不同的结果

时间:2018-05-22 09:54:05

标签: mysql sql select case

我有以下查询:

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

我需要的是从查询中返回一行,这样如果firstConditionKey不为空,那么行就像min(firstConditionKey),因为我不关心它是哪一行,只要它是它是一行firstConditionKey,否则,如果没有firstconditionKey的行,则返回有secondConditionKey的行或如果没有则返回任何行。< / p>

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

1 个答案:

答案 0 :(得分:1)

如果您想要一行,可以使用order bylimit。所以,基本的想法是:

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;
相关问题