【问题标题】:select different results based on condition根据条件选择不同的结果
【发布时间】:2018-11-01 01:10:28
【问题描述】:

我有以下疑问:

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

我需要从查询中返回单行,因此如果firstConditionKey 不为空,则该行将类似于min(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 的第一行。

【问题讨论】:

  • 我不熟悉 mysql,但我想我会在内部查询中创建一个附加字段,该字段的值为 2 of first exists 或 1 if only second did else 0,然后带来一行具有该字段的最大值。
  • 可能是SELECT ... FROM (SELECT ... WHERE <first condition> UNION ALL SELECT ... WHERE <second condition>) LIMIT 1 之类的?
  • 我强烈建议提供示例数据。从您的子查询创建各种示例结果,然后显示您需要的输出。 stackoverflow.com/help/mcve
  • 添加这个,然后在外层顺序中限制1:,当firstConditionKey不为空时为2,当secondConditionkey不为空时为2,否则为0优先结束,
  • @GeorgeMenoutis 谢谢。按顺序过滤!

标签: mysql sql select case


【解决方案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;

【讨论】:

  • 已经做了类似的事情,但这就是答案!谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-12
  • 1970-01-01
  • 1970-01-01
  • 2014-11-26
  • 1970-01-01
  • 1970-01-01
  • 2022-01-23
相关资源
最近更新 更多