Return 空值 IN 子句 mysql

Return null values IN clause mysql

在数据库中找不到数据时打印未找到。例如在我的数据库中我没有 56443 因此它应该打印 'not found'

SELECT uid, (CASE WHEN (u.uid = null) THEN 'not found' ELSE 'found' END) as result
FROM (SELECT uid
            FROM users
            WHERE uid IN (1,2,56443,3)) as u;

得到结果如下

+--------+--------+
| uid    | result|
+--------+--------+
| 1      | found | 
| 2      | found |
| 3      | found |
+--------+--------+

我也期待 not found56443

那是因为您正在将一个值与 null aka 进行比较。未知。与空值进行比较时始终使用 IS 运算符。 CASE WHEN (u.uid is null) THEN 'not found' ELSE 'found' END) as result

试试这个(更新的答案):

SELECT u2.uid, (CASE WHEN (u1.uid is null) THEN 'not found' ELSE 'found' END) 
as     result
FROM users u1
RIGHT JOIN 
(select 1 as uid union all
 select 2 as uid union all
 select 3 as uid union all
 select 56443 as uid
) u2
on u1.uid = u2.uid

您需要使用不同的方法。您将需要使用 UNION ALL 创建一个包含所有值的内联视图,然后将其与用户 table:

左连接

SQL Fiddle

查询 1:

SELECT a.uid, (CASE WHEN (u.uid is null) THEN 'not found' ELSE 'found' END) as     result
FROM (select 1 as UID FROM dual
      UNION ALL
      select 2 as UID FROM dual
      UNION ALL
      select 56443 as UID FROM dual
      UNION ALL
      select 3 as UID FROM dual) as a
LEFT JOIN users u on a.uid = u.uid

[结果]:

|   UID |    result |
|-------|-----------|
|     1 |     found |
|     2 |     found |
|     3 |     found |
| 56443 | not found |