简体   繁体   中英

mysql distinct values without empty string and NULL

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.

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 != '';

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  

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 !='';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM