【问题标题】:How to use sql different where statement on the basis of column's value?如何根据列的值使用sql不同的where语句?
【发布时间】:2020-04-06 13:06:57
【问题描述】:

我有一个名为offers的表。它有以下列

  1. is_special 的值为真或假
  2. normal_expiry_date 具有日期值
  3. special_expiry_date 具有日期值

现在如果行有is_special = false,那么我想使用where normal_expiry_date > current_date,如果 is_special = true 然后where special_expiry_date > current_date

非常感谢你,即使你试图提供帮助

【问题讨论】:

  • 请不要向数据库标签发送垃圾邮件:mysql oracle postgresql。您实际使用的是哪一种?
  • @ShaheryarAhmed 。 . .我删除了不一致的数据库标签。请仅使用您正在使用的数据库进行标记。
  • 从性能和复杂性的角度来看,我会努力避免这样的设计,有条件地与一列或另一列进行比较。我更愿意与单个 expiry_date 列进行比较。但如果这不可能,那么我至少会避免 OR 条件,并将 current_date 与单个表达式进行比较,例如current_date < CASE WHEN ... THEN t.special_expiry_date WHEN ... THEN t.normal_expiry_date ELSE ... END ,对于某些数据库,可以创建基于函数的索引,就好像该表达式是单列一样。

标签: sql knex.js


【解决方案1】:

一个选项是

where current_date < case when is_special = false then normal_expiry_date
                          when is_special = true  then special_expiry_date
                     end

【讨论】:

    【解决方案2】:

    你可以使用布尔逻辑:

    where 
        (is_special = 'false' and normal_expiry_date > current_date)
        or (is_special = 'true' and special_expiry_date  > current_date)
    

    注意:不清楚is_specia 的数据类型是什么,因此您可能需要调整相等条件。如果那是 Postgres 布尔值,例如:

    where 
        (not is_special and normal_expiry_date > current_date)
        or (is_special and special_expiry_date  > current_date)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-26
      • 1970-01-01
      • 2020-01-08
      • 2013-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多