MySQL: select * from table where col IN (null, "") 可能没有 OR

发布于 2024-08-19 05:01:11 字数 176 浏览 7 评论 0 原文

是否可以在不使用 or 的情况下在 MySQL 中对空字符串和 NULL 值进行选择?

这:

   select * from table where col IN (null, "");

不起作用,它忽略 null (或者可能将其与字符串“null”匹配)。

Is it somehow possible to do a select for empty strings and NULL values in MySQL without using or?

This:

   select * from table where col IN (null, "");

doesn't work, it ignores the null (or possibly matches it with the string 'null').

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

も让我眼熟你 2024-08-26 05:01:11
SELECT  *
FROM    mytable
WHERE   COALESCE(col, '') = ''

但请注意,如果列已建立索引,则 OR 查询的效率会高得多:

SELECT  *
FROM    mytable
WHERE   col = '' OR col IS NULL

这将使用索引上的 ref_or_null 访问路径。

如果您需要从值列表中选择 NULL,只需将所有非空值放入列表中并添加一个 OR IS NULL 条件:

SELECT  *
FROM    mytable
WHERE   col IN ('val1', 'val2', 'val3') OR col IS NULL

这将使用还有 col 上的索引。

SELECT  *
FROM    mytable
WHERE   COALESCE(col, '') = ''

Note, however, than OR query will be much more efficient if the column is indexed:

SELECT  *
FROM    mytable
WHERE   col = '' OR col IS NULL

This will use ref_or_null access path on the index.

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:

SELECT  *
FROM    mytable
WHERE   col IN ('val1', 'val2', 'val3') OR col IS NULL

This will use an index on col as well.

简单气质女生网名 2024-08-26 05:01:11

如果其他人像我一样正在寻找这个解决方案;如果您要按多列进行搜索,则需要将 where/or 语句分组在括号中。

这不会返回您期望的结果:

SELECT * 
FROM table 
WHERE col1 IN ('val1', 'val2') OR col1 IS NULL AND col2 IN ('val3', 'val4')

“OR col1 IS NULL”将完全覆盖您的“AND col2 IN”语句。

将 col1 的所有条件放在括号内是可行的:

SELECT * 
FROM table 
WHERE (col1 IN ('val1', 'val2') OR col1 IS NULL) AND col2 IN ('val3', 'val4') 

我花了一段时间才考虑尝试这个,因为(至少根据我的经验)你通常不会将 WHERE 语句放在括号内。

In case anyone else is looking for this solution, as I was; if you're searching by more than one column, you need to group the where/or statement in parenthesis.

This will not return the results you expect:

SELECT * 
FROM table 
WHERE col1 IN ('val1', 'val2') OR col1 IS NULL AND col2 IN ('val3', 'val4')

The "OR col1 IS NULL" will completely override your "AND col2 IN" statement.

Putting all of the conditions for col1 inside parenthesis will work:

SELECT * 
FROM table 
WHERE (col1 IN ('val1', 'val2') OR col1 IS NULL) AND col2 IN ('val3', 'val4') 

It took me a while to consider trying this, because (at least in my experience) you don't typically put WHERE statements in parenthesis.

星星的轨迹 2024-08-26 05:01:11

这对我来说很棒

SELECT *
FROM table
WHERE IFNULL(col1, '-') IN('val1', 'val2', '-') AND col2 IN ('val3', 'val4')

That's work great for me

SELECT *
FROM table
WHERE IFNULL(col1, '-') IN('val1', 'val2', '-') AND col2 IN ('val3', 'val4')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文