Return null values IN clause mysql

那年仲夏 提交于 2019-12-24 00:38:26

问题


Print not found when there is no data found in database. For example in my database I do not have 56443 therefore it should print '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;

Getting result as follows

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

I am also expecting not found row with 56443


回答1:


You need to use a different approach. You will need to create a inline view with all the values using the UNION ALL, and then left join it with the users table:

SQL Fiddle

Query 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

[Results]:

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



回答2:


That is because you are comparing a value with null aka. unknown. Always use the IS operator when comparing to null values. CASE WHEN (u.uid is null) THEN 'not found' ELSE 'found' END) as result

Try this instead (updated answer):

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


来源:https://stackoverflow.com/questions/36324503/return-null-values-in-clause-mysql

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