mysql NULL value in where in CLAUSE

别等时光非礼了梦想. 提交于 2020-04-09 06:20:08

问题


how to deal with NULL value in mysql where in CLAUSE

i try like

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

it not working

only work like :

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

how can i get it work in WHERE IN ? it is possible ?


回答1:


As by my understanding you want to pull every record with 1,2,3 and null value.

I don't think its possible to put null in the IN operator. Its expects values and null is well.. not a value. So You really have to put the OR with the null to get the desired result.




回答2:


Maybe this information from the MySQL Reference Manual helps:

To comply with the SQL standard, IN returns NULL not only if the expression on the left hand side is NULL, but also if no match is found in the list and one of the expressions in the list is NULL.




回答3:


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.




回答4:


Following statement should help:

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


来源:https://stackoverflow.com/questions/3913364/mysql-null-value-in-where-in-clause

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!