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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM