If else on WHERE clause

前端 未结 5 1855
栀梦
栀梦 2020-12-09 01:53

I\'ve this query:

SELECT  `id` ,  `naam` 
FROM  `klanten` 
WHERE (
`email` LIKE  \'%@domain.nl%\'
OR  `email2` LIKE  \'%@domain.nl%\'
)

But

5条回答
  •  难免孤独
    2020-12-09 02:20

    You want to use coalesce():

    where coalesce(email, email2) like '%anja@fiskkoer.nl%'
    

    If you want to handle empty strings ('') versus NULL, a case works:

    where (case when email is NULL or email = '' then email2 else email end) like '%anja@fiskkoer.nl%'
    

    And, if you are worried about the string really being just spaces:

    where (case when email is NULL or ltrim(email) = '' then email2 else email end) like '%anja@fiskkoer.nl%'
    

    As an aside, the sample if statement is really saying "If email starts with a number larger than 0". This is because the comparison is to 0, a number. MySQL implicitly tries to convert the string to a number. So, 'abcd@de.com' would fail, because the string would convert as 0. As would '0abc@de.com'. But, '1abc@de.com' and '01abc@de.com' would succeed.

提交回复
热议问题