zoukankan      html  css  js  c++  java
  • MySQL使用IF函数来动态执行where条件

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

  • 相关阅读:
    Android_SQLite标准版
    AutoMapper
    ext.net实例
    Winform Ribbon开发
    数据仓库建设之《元数据管理》
    数据仓库建设之维度建模
    数据仓库建设之总方案
    一点感想
    详细探秘Linux 和 Window 双系统访问Windows 磁盘需要输入密码问题解决过程分析
    如何把数据放到C#的心里之 DB2实例
  • 原文地址:https://www.cnblogs.com/codecat/p/12103250.html
Copyright © 2011-2022 走看看