在 MyBatis 中,如果子句为 null,我该如何跳过查询?

How can I skip query if clause is null in MyBatis?

提问人:mentha 提问时间:10/22/2023 最后编辑:mentha 更新时间:10/22/2023 访问量:40

问:

选择查询的结果如下所示。 total 列将包含每行的总和。

day_1 day_2 day_3
[空] 6 [空] 6
[空] [空] [空] 0

为了找到总值,我使用了下面的函数。

(
  <foreach item="item" collection="dayList" open="" separator=" + " close="">
            COALESCE(day_${item}, 0)
  </foreach>
) AS total

我想要的结果如下图所示。 如果一行中的所有项目都是 NULL,我希望显示 NULL 值。

day_1 day_2 day_3
[空] 6 [空] 6
[空] [空] [空] [空]

我想如果这样做 我预料到了

    (
      <foreach item="item" collection="dayList" open="" separator=" + " close="">
     <if test="#{'hour_' + item} != null">
        hour_${item}
     </if>
      </foreach>
    ) AS total

结果只会添加非 null 的内容。

Java MyBatis

评论

0赞 ave 10/23/2023
您可能需要添加一个 NULL 检查,即 .最好用 Java 代码进行计算。顺便说一句,无法检查列值,因为在执行查询之前会评估条件。... case when coalesce(day_1, day_2, day_3) then coalesce(day_1, 0) + coalesce(day_2, 0) + coalesce(day_3, 0) else null end as totaltotal<if><if>

答:

0赞 Zeeshan Arif 10/22/2023 #1

试试这个

(
  <foreach item="item" collection="dayList" open="" separator=" + " close="">
            COALESCE(day_${item}, null)
  </foreach>
) AS total

评论

0赞 mentha 10/23/2023
如果我这样做,当 null + 6 时不会出现 null 值吗?