我有以下查询:
select a,b,c,firstConditionKey,secondConditionkey from
(select ..... - big query - ..... ) as main;
我需要的是从查询中返回一行,所以如果 firstConditionKey
不为空,该行将类似于 min(firstConditionKey)
因为我不知道只要它是具有 firstConditionKey
的行,就不必关心它是哪一行,否则,如果没有具有 firstconditionKey
的行,则返回包含 firstConditionKey
的行有一个 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
的第一行。
最佳答案
如果你想要一行,你可以使用order by
和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;
关于mysql - 根据条件选择不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50464749/