mysql NULL value in where in CLAUSE

前端 未结 4 1453
挽巷
挽巷 2021-01-04 04:59

how to deal with NULL value in mysql where in CLAUSE

i try like

SELECT * FROM mytable WHERE field IN(1,2,3,NULL)
<         


        
4条回答
  •  一向
    一向 (楼主)
    2021-01-04 05:31

    There is a MySQL function called COALESCE. It returns the first non-NULL value in the list, or NULL if there are no non-NULL values.

    If you for example run SELECT COALESCE(NULL, NULL, -1); you will get -1 back because it's the first non-NULL value.

    So the trick here is to wrap your expression in COALESCE, and add a value as the last parameter that you also add in your IN function.

    SELECT * FROM mytable WHERE COALESCE(field,-1) IN (1,2,3,-1)
    

    It will only match if field is 1,2 or 3, or if field is NULL.

提交回复
热议问题