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