mysql distinct values without empty string and NULL

别来无恙 提交于 2021-02-18 18:15:11

问题


How to retrieve mysql distinct values without empty string value and NULL value

SELECT 
DISTINCT CON.EMAILADDRESS AS 'E-MAIL'
FROM  STUDENT
INNER JOIN CONTACT CON ON STUDENT.CONTACT_ID = CON.ID
WHERE
(CON.EMAILADDRESS IS NOT NULL 
OR  CON.EMAILADDRESS !=' ');

But in output still getting empty e-mails too. Can't figure out what wrong I am doing.


回答1:


Try this:

SELECT 
DISTINCT CON.EMAILADDRESS AS 'E-MAIL'
FROM  STUDENT AST
INNER JOIN CONTACT CON ON AST.CONTACT_ID = CON.ID
WHERE length(trim(CON.EMAILADDRESS)) >0 and CON.EMAILADDRESS IS NOT NULL  



回答2:


Your only problem is that you use OR instead of AND.

Let's look at the case where the value is NULL:

  • CON.EMAILADDRESS IS NOT NULL => FALSE
  • CON.EMAILADDRESS != ' ' => NULL

FALSE OR NULL => NULL. As the criteria doesn't result in TRUE you don't select NULLs.

And if the value is an empty string '', ' ', or whatever length:

  • CON.EMAILADDRESS IS NOT NULL => TRUE
  • CON.EMAILADDRESS != ' ' => FALSE

TRUE OR FALSE => TRUE. You select the empty string.

I suppose this is what confused you: in spite of having mistakenly used OR instead of AND you still removed some empty strings, but not all.

So:

WHERE CON.EMAILADDRESS IS NOT NULL AND CON.EMAILADDRESS != ' ';

Or, as any string != '' can't be NULL (NULL != '' => NULL, not TRUE), simply:

WHERE CON.EMAILADDRESS != '';



回答3:


AND

SELECT DISTINCT CON.EMAILADDRESS AS 'E-MAIL'
FROM STUDENT AST
INNER JOIN CONTACT CON ON AST.CONTACT_ID = CON.ID
WHERE CON.EMAILADDRESS IS NOT NULL  
AND CON.EMAILADDRESS !=' '
AND CON.EMAILADDRESS !='';


来源:https://stackoverflow.com/questions/28169612/mysql-distinct-values-without-empty-string-and-null

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