服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

Mysql|Sql Server|Oracle|Redis|MongoDB|PostgreSQL|Sqlite|DB2|mariadb|Access|数据库技术|

服务器之家 - 数据库 - Mysql - MySQL使用IF函数动态执行where条件的方法

MySQL使用IF函数动态执行where条件的方法

2022-11-21 17:09不忘初心,砥砺前行 Mysql

这篇文章主要介绍了MySQL使用IF函数来动态执行where条件,详细介绍了IF函数在WHERE条件中的使用,MySQL的IF()函数,接受三个表达式,如果第一个表达式为true,而不是零且不为NULL,它将返回第二个表达式,需要的朋友可以参考下

IF函数

IF(expression ,expr_true, expr_false);

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

IF函数在WHERE条件中的使用

先来看一个SQL:

select book_name,read_status from t_book;

结果如下:

MySQL使用IF函数动态执行where条件的方法

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

下面使用IF函数来查询:

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

MySQL使用IF函数动态执行where条件的方法

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

MySQL使用IF函数动态执行where条件的方法

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

MySQL使用IF函数动态执行where条件的方法

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

MySQL使用IF函数动态执行where条件的方法

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目的。

到此这篇关于MySQL使用IF函数来动态执行where条件的文章就介绍到这了,更多相关MySQL动态执行where条件内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文地址:https://www.cnblogs.com/codecat/p/12103250.html

延伸 · 阅读

精彩推荐