MySQL IN 子句中的多个列具有空值
MySQL multiple columns in IN clause with null values
我想查询两列作为 2-tuples ,其中一个可以为空。
示例:
+-------------------------+
| first | last |
+-------------------------+
| Homer | NULL |
| Marge | Simpson |
+-------------------------+
类似于:
Select * from cartoons where (first, last ) in ((Homer ,NULL ), ( Marge ,Simpson) ) ;
(应该检索 Homer 和 Marge 的行)
我正在使用以下查询进行测试:
select ('Homer', null) in (('Homer', null));
其中 returns 为空。
相关问题参考:
- Why MYSQL IN keyword not considering NULL values
SQL 版本:5.7.12
在这种情况下您不能使用元组语法,它在幕后使用相等比较。相反,使用更长的版本:
SELECT *
FROM cartoons
WHERE first = 'Homer' AND last IS NULL OR first = 'Marge' AND last = 'Simpson';
仅供参考,以下是您当前查询的实际内容:
SELECT *
FROM cartoons
WHERE first = 'Homer' AND last = NULL OR first = 'Marge' AND last = 'Simpson';
请注意,将列直接与 NULL
进行比较在语义上是不正确的。
试试这个:
SELECT * FROM cartoons WHERE (first in (Array1) AND last IS NULL) OR (last in (Array2) AND first IS NULL) OR (first in (Array1) AND last in (Array2));
SELECT *
FROM cartoons
JOIN ( SELECT 'Homer' first, NULL last
UNION ALL
SELECT 'Marge', 'Simpson' ) criteria ON cartoons.first <=> criteria.first
AND cartoons.last <=> criteria.last
使用 NULL
安全比较,在 MySQL 中使用 <=>
。假设只有第二列可以为NULL:
Select c.*
from cartoons c
where (first = 'Homer' and last <=> NULL) or
(first = 'Marge' and last <=> 'Simpson')\;
我想查询两列作为 2-tuples ,其中一个可以为空。
示例:
+-------------------------+
| first | last |
+-------------------------+
| Homer | NULL |
| Marge | Simpson |
+-------------------------+
类似于:
Select * from cartoons where (first, last ) in ((Homer ,NULL ), ( Marge ,Simpson) ) ;
(应该检索 Homer 和 Marge 的行)
我正在使用以下查询进行测试:
select ('Homer', null) in (('Homer', null));
其中 returns 为空。
相关问题参考:
- Why MYSQL IN keyword not considering NULL values
SQL 版本:5.7.12
在这种情况下您不能使用元组语法,它在幕后使用相等比较。相反,使用更长的版本:
SELECT *
FROM cartoons
WHERE first = 'Homer' AND last IS NULL OR first = 'Marge' AND last = 'Simpson';
仅供参考,以下是您当前查询的实际内容:
SELECT *
FROM cartoons
WHERE first = 'Homer' AND last = NULL OR first = 'Marge' AND last = 'Simpson';
请注意,将列直接与 NULL
进行比较在语义上是不正确的。
试试这个:
SELECT * FROM cartoons WHERE (first in (Array1) AND last IS NULL) OR (last in (Array2) AND first IS NULL) OR (first in (Array1) AND last in (Array2));
SELECT *
FROM cartoons
JOIN ( SELECT 'Homer' first, NULL last
UNION ALL
SELECT 'Marge', 'Simpson' ) criteria ON cartoons.first <=> criteria.first
AND cartoons.last <=> criteria.last
使用 NULL
安全比较,在 MySQL 中使用 <=>
。假设只有第二列可以为NULL:
Select c.*
from cartoons c
where (first = 'Homer' and last <=> NULL) or
(first = 'Marge' and last <=> 'Simpson')\;