如果在WHERE子句上则为else

bot*_*wer 27 mysql sql if-statement

我有这个问题:

SELECT  `id` ,  `naam` 
FROM  `klanten` 
WHERE (
`email` LIKE  '%@domain.nl%'
OR  `email2` LIKE  '%@domain.nl%'
)
Run Code Online (Sandbox Code Playgroud)

但我想做这样的事情:

SELECT  `id` ,  `naam` 
FROM  `klanten` 
WHERE IF(`email` > 0,
`email` LIKE  '%@domain.nl%'
,  `email2` LIKE  '%@domain.nl%'
)
Run Code Online (Sandbox Code Playgroud)

如何检查电子邮件是否存在?我想使用电子邮件,如果此字段为空,我想使用email2.我该如何做到这一点?

Roc*_*mat 47

IF用于选择字段,然后将LIKE子句放在它之后:

SELECT  `id` ,  `naam` 
FROM  `klanten` 
WHERE IF(`email` != '', `email`, `email2`) LIKE  '%@domain.nl%'
Run Code Online (Sandbox Code Playgroud)


Gor*_*off 9

你想用coalesce():

where coalesce(email, email2) like '%anja@fiskkoer.nl%'
Run Code Online (Sandbox Code Playgroud)

如果你想处理空字符串('')与NULL,一个案例有效:

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

而且,如果你担心字符串真的只是空格:

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

顺便if说一下,示例语句实际上是在说"如果电子邮件以大于0的数字开头".这是因为比较是0,一个数字.MySQL隐式尝试将字符串转换为数字.因此,'abcd@de.com'会失败,因为该字符串将转换为0.与'0abc@de.com'一样.但是,'1abc@de.com'和'01abc@de.com'会成功.