问题
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
=> FALSECON.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
=> TRUECON.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