zoukankan      html  css  js  c++  java
  • MySQL取两列的较小值或者较大值

      今偶遇这样一场景,两列都是日期时间类型,需要通过判断这两个日期的大小来取值。为了更好地说明这个流程,我们就假设去两列日期时间中较大者。那如何通过一条SQL语句搞定呢?此时,就需要借助IF-ELSE的思路了,请看示例代码:

      (1)方式一

    SELECT if(col_date_1 > col_date_2, col_date_1, col_date_2) as max_time
    FROM table_name
    WHERE some_col = 'some_value'
    

      若是要从三个日期时间中挑选出最大时间值,那又如何处理呢?此时,可以借助IF的嵌套,请看示例代码:

    SELECT if(col_date_1 > col_date_2, if(col_date_1 > col_date_3, col_date_1, col_date_3), if(col_date_2 > col_date_3, col_date_2, col_date_3) as max_time
    FROM table_name
    WHERE some_col = 'some_value'

      (2)方式二

    SELECT case when col_date_1 > col_date_2 then col_date_1 else col_date_2 end as max_time
    FROM table_name
    WHERE some_col = 'some_value'

      通过上述语句就可以完成想要的结果了,若还有其它简洁方式,可以共享一下,谢谢。

      若想要当前时间加一年,那么可以通过DATE_ADD函数来处理,例如DATE_ADD(NOW(), interval 1 year)。

  • 相关阅读:
    hdu 3371 Connect the Cities
    hust 1102 Constructing Roads
    hdu 1856 More is better
    hdu 1325 Is It A Tree?
    poj 2828 Buy Tickets (线段树)
    sdut 2351 In Danger (找规律)
    poj 2528 Mayor's posters(线段树)
    poj 2352 Stars (树状数组)
    poj 2492 A Bug's Life (并查集)
    poj 1703 Find them, Catch them(并查集)
  • 原文地址:https://www.cnblogs.com/bien94/p/12897899.html
Copyright © 2011-2022 走看看