1. 程式人生 > 實用技巧 >建立時間和更新時間兩個選一個的情況和select case when ... then ... else ... end from 表 的使用

建立時間和更新時間兩個選一個的情況和select case when ... then ... else ... end from 表 的使用

1、查詢時間,如果更新時間update_time為空就查建立時間create_time,否則查更新時間update_time

select update_time,create_time, case when (update_time is null or update_time = '') then create_time else update_time end from 表名;

2、當更新時間和建立時間為判斷條件且如果更新時間為空就時就根據建立時間來判斷,否則用更新時間判斷

select * from 表名 t where (
(t.update_time is null or t.update_time = ''
) and t.create_time > to_date('2020-08-13','yyyy-MM-dd') and t.create_time < to_date('2020-08-14', 'yyyy-MM-dd')) or (t.update_time > to_date('2020-08-13', 'yyyy-MM-dd') and t.update_time < to_date('2020-08-14', 'yyyy-MM-dd'))

3、上面的sql語句在xml中的表示如下:

<select id="selectByConditions" resultMap="result_Map
"> SELECT * FROM 表名 where del_flag=0 and line_type=#{lineType} and ( ((update_time is null or update_time = '') <if test="null != startTime"> and create_time &gt;= #{startTime} </if> <if test="null != endTime"> and create_time
&lt;= #{endTime} </if>) or ( 1=1 <if test="null != startTime"> and update_time &gt;= #{startTime} </if> <if test="null != endTime"> and update_time &lt;= #{endTime} </if>) ) ORDER BY update_time desc, create_time desc </select>