mysql - 根据条件选择不同的结果

标签 mysql sql select case

我有以下查询:

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 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;

关于mysql - 根据条件选择不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50464749/

相关文章:

mysql - 获取具有特定 revision_status 的行

php - php 和 mysql 页面中的性能问题

php - SQL/PHP 如果不满足条件则选择所有内容

mysql - 将一列中的字符串拆分为同一表中的三列并插入到新表中

sql - 如何在 UPDATE 语句的集合列表中使用聚合

php - 我的 SELECT COUNT 查询返回一个数组而不是整数

sql-server - SQL : Using three SELECT statements in a single query

mysql - 有没有办法重置 MySQL 中的所有配置?

php - JOIN 在三个表上不起作用

sql-server - 计算总返回率 0