Mysql:从表中选择 * 其中 col IN (null, "") 可能没有 OR
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2147824/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mysql: select * from table where col IN (null, "") possible without OR
提问by pvgoddijn
is its somehow possible to do a select for empty strings and NULL values in Mysql without using or?
是否可以在不使用 or 的情况下对 Mysql 中的空字符串和 NULL 值进行选择?
this:
这个:
select * from table where col IN (null, "");
doesnt work, it ignores the null (or possibly matches it with the string 'null'
不起作用,它忽略空值(或可能将它与字符串“空”匹配
thanks, P.V. Goddijn
谢谢,PV Goddijn
回答by Quassnoi
SELECT *
FROM mytable
WHERE COALESCE(col, '') = ''
Note, however, than OR
query will be much more efficient if the column is indexed:
但是请注意,OR
如果对列进行索引,则查询效率会更高:
SELECT *
FROM mytable
WHERE col = '' OR col IS NULL
This will use ref_or_null
access path on the index.
这将使用ref_or_null
索引上的访问路径。
If you need to select from a list of values along with NULLs
, just put all not-null values into the list and add a single OR IS NULL
condition:
如果您需要从值列表中选择NULLs
,只需将所有非空值放入列表并添加一个OR IS NULL
条件:
SELECT *
FROM mytable
WHERE col IN ('val1', 'val2', 'val3') OR col IS NULL
This will use an index on col
as well.
这也将使用索引col
。