惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

美团技术团队
T
The Blog of Author Tim Ferriss
C
Check Point Blog
博客园_首页
J
Java Code Geeks
云风的 BLOG
云风的 BLOG
L
LangChain Blog
小众软件
小众软件
Stack Overflow Blog
Stack Overflow Blog
爱范儿
爱范儿
Vercel News
Vercel News
博客园 - Franky
V
V2EX
IT之家
IT之家
U
Unit 42
N
Netflix TechBlog - Medium
腾讯CDC
Apple Machine Learning Research
Apple Machine Learning Research
Microsoft Azure Blog
Microsoft Azure Blog
罗磊的独立博客
博客园 - 叶小钗
H
Help Net Security
V
Visual Studio Blog
GbyAI
GbyAI

博客园 - 代码猫

Spring boot 打成jar包,并运行jar包。 MySQL中两个DateTime字段相减,得到秒,分,天数 mybatis中大于等于小于等于的写法 Spring boot 自定义注解,Java通过反射获取注解,及注解的说明,附源码下载! Spring boot 自定义注解+@Aspect实现切面输出日志,附源码下载! HTML5 Canvas基础教程 SpringBoot+Jpa动态切换多数据源配置及实现 MySQL使用DATE_FORMAT()函数格式化日期 Java List转String数组与String数组转List JPA忽略实体类某属性,不持久化某字段的解决方法 git 常用命令 Windows系统CMD窗口下,MySQL建库、还原数据库命令操作示例 Java JPA 报java.lang.IllegalArgumentException: Validation failed for query for method public abstract ...异常的一种原因和解决办法 MySQL 5.7 执行SQL报错:1055 - Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 的解决办法 Java8使用实现Runnable接口方式创建新线程的方法 windows查看端口被占用情况 Windows环境下设置Tomcat8以服务的形式运行,不再打开Tomcat窗口 MySql添加字段命令 Java中String、LocalDateTime、LocalDate、Date互转
MySQL使用IF函数来动态执行where条件
代码猫 · 2020-04-13 · via 博客园 - 代码猫

IF函数

IF(expression ,expr_true, expr_false);

MySQL的IF()函数,接受三个表达式,如果第一个表达式为true,而不是零且不为NULL,它将返回第二个表达式。否则,它返回第三个表达式。根据使用它的上下文,它返回数字或字符串值。

IF函数在WHERE条件中的使用

先来看一个SQL:

select book_name,read_status from t_book;

结果如下:

read_status字段意思是阅读状态,有以下几个值: 0(未阅读),1(阅读中),2(已阅读)。

下面使用IF函数来查询:

# 查询未阅读的book
select book_name,read_status from t_book where IF(-1 = 0, true, read_status = 0);

# 查询阅读中的book
select book_name,read_status from t_book where IF(-1 = 1, true, read_status = 1);

# 查询已阅读的book
select book_name,read_status from t_book where IF(-1 = 2, true, read_status = 2);

# 查询全部的book
select book_name,read_status from t_book where IF(-1 = -1, true, read_status = -1);

JAVA使用

/**
 * 根据阅读状态来查询book
 * @param readStatus
 * @return
 */
@Query(value = "select book_name,read_status from t_book where IF(-1 = :readStatus, true, read_status = readStatus)", nativeQuery = true)
List<TBook> queryByReadStatus(@Param("readStatus") String readStatus);

这样可以通过传入readStatus的值来控制是否执行read_status条件,当传值为-1时,不执行 read_status = -1 条件,而是执行 true,相当于忽略了read_status条件,达到查询全部状态的book目的。