<select id="selectAppFeedList" parameterType="AppFeed" resultMap="AppFeedResult">…
- User
- Assistant
你的写法在
<where>标签内部使用了<if>语句来添加条件,这是正确的。但是在SQL语句中,你不需要使用"and"在<where>标记内部的最开始,因为MyBatis会根据条件的存在自动地在生成的SQL语句中插入它。另一方面,你的时间过滤条件的逻辑看起来似乎不太对,它当前每次查询时都会将时间限定在服务器当前日期的早上8点到次日晚上8点内。如果你想要统计某个给定日期的早上8点到晚上8点的进食总量,正确的做法是将你想要查询的日期通过参数传进来,而不是使用CURDATE()这种方式,除非你总是需要的是服务器当前日期的数据。
以下是根据你提供的代码和你的需求改写的SQL片段:
<select id="selectAppFeedList" parameterType="AppFeed" resultMap="AppFeedResult"> <include refid="selectAppFeedVo"/> <where> <if test="logType != null"> log_type = #{logType} </if> <if test="babyId != null"> <choose> <when test="logType != null"> AND </when> <otherwise> </otherwise> </choose> baby_id = #{babyId} </if> <if test="startDate != null"> <choose> <when test="logType != null or babyId != null"> AND </when> <otherwise> </otherwise> </choose> <![CDATA[ feed_time >= #{startDate} + INTERVAL 8 HOUR AND feed_time < DATE_ADD(#{startDate}, INTERVAL 32 HOUR) ]]> </if> </where> ORDER BY feed_time DESC </select> - User
但是也不对,我想要的是 我传入的比如是2023-03-12 07:00:00,我应该查的是2023-03-11 08:00至2023-03-12 08:00 如果我传入的是2023-03-12 09:00:00,我应该查的是2023-03-12 08:00至2023-03-13 08:00
- Assistant
根据你的描述,你需要根据传入的时间来确定查询的时间范围。如果传入的时间是早上8点前,你需要从前一天的早上8点查询到传入日期当天的早上8点;如果是早上8点后,你需要从传入日期当天的早上8点查询到次日的早上8点。
查询的SQL语句应该根据传入的时间动态调整时间范围。这可以通过MyBatis的
<choose>标签来实现。下面是改进过的SQL查询:<select id="selectAppFeedList" parameterType="AppFeed" resultMap="AppFeedResult"> <include refid="selectAppFeedVo"/> <where> <if test="logType != null"> log_type = #{logType} </if> <if test="babyId != null"> AND baby_id = #{babyId} </if> <if test="inputTime != null"> AND feed_time BETWEEN <choose> <when test="inputTime.toLocalDateTime().getHour() < 8"> <!-- 如果传入的时间是早上8点前,则查询的开始时间是前一天的早上8点 --> #{inputTime.toLocalDateTime().minusDays(1).withHour(8).format(DateTimeFormatter.ofPattern('yyyy-MM-dd HH:mm:ss'))} </when> <otherwise> <!-- 如果传入的时间是早上8点后,则查询的开始时间是当天的早上8点 --> #{inputTime.toLocalDateTime().withHour(8).format(DateTimeFormatter.ofPattern('yyyy-MM-dd HH:mm:ss'))} </otherwise> </choose> AND <choose> <when test="inputTime.toLocalDateTime().getHour() < 8"> <!-- 如果传入的时间是早上8点前,则查询的结束时间是传入日期当天的早上8点 --> #{inputTime.toLocalDateTime().withHour(8).format(DateTimeFormatter.ofPattern('yyyy-MM-dd HH:mm:ss'))} </when> <otherwise> <!-- 如果传入的时间是早上8点后,则查询的结束时间是次日的早上8点 --> #{inputTime.toLocalDateTime().plusDays(1).withHour(8).format(DateTimeFormatter.ofPattern('yyyy-MM-dd HH:mm:ss'))} </otherwise> </choose> </if> </where> ORDER BY feed_time DESC </select>