mysql - 根据条件选择不同的结果
问题描述
我有以下查询:
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
。
解决方案
如果你想要一行,你可以使用order by
and 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;
推荐阅读
- python - 在远程主机上监听 rabbitmq 队列
- angular - 在 mat-table 中添加列而不影响 previos 列数据
- angular - (ngx-admin/Nebular) 如何删除我的自定义登录组件上的后退按钮?
- javascript - 移动到 d3 v5 后,颜色后代节点和链接断开
- angular - 如何将 StropheJs 与 Angular 8 集成
- php - 使用 Ajax 技术基于所选 ID 的文本加载不起作用
- python - 尝试使用 nltk 在 python 中标记特殊情况的句子
- julia - DynamicalSystems 初始条件不工作的轨道图
- excel - VBA Excel 在 Internet Explorer 中查找搜索的选项卡
- java - 无法从数据库结果集中设置 Textview 文本