If else on WHERE clause

前端 未结 5 1836
栀梦
栀梦 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.

    0 讨论(0)
  • 2020-12-09 02:20

    Here is a sample query for a table having a foreign key relationship to the same table with a query parameter.

    SET @x = -1;
    SELECT id, categoryName 
    FROM Catergory WHERE IF(@x > 0,category_ParentId = @x,category_ParentId IS NOT NULL);
    

    @x can be changed.

    0 讨论(0)
  • 2020-12-09 02:22

    IF is used to select the field, then the LIKE clause is placed after it:

    SELECT  `id` ,  `naam` 
    FROM  `klanten` 
    WHERE IF(`email` != '', `email`, `email2`) LIKE  '%@domain.nl%'
    
    0 讨论(0)
  • 2020-12-09 02:29

    Note the following is functionally different to Gordon Linoff's answer. His answer assumes that you want to use email2 if email is NULL. Mine assumes you want to use email2 if email is an empty-string. The correct answer will depend on your database (or you could perform a NULL check and an empty-string check - it all depends on what is appropriate for your database design).

    SELECT  `id` ,  `naam` 
    FROM  `klanten` 
    WHERE `email` LIKE  '%anja@fiskkoer.nl%'
    OR (LENGTH(email) = 0 AND `email2` LIKE  '%anja@fiskkoer.nl%')
    
    0 讨论(0)
  • 2020-12-09 02:38

    try this ,hope it helps

    select user_display_image as user_image,
    user_display_name as user_name,
    invitee_phone,
    (
     CASE 
        WHEN invitee_status=1 THEN "attending" 
        WHEN invitee_status=2 THEN "unsure" 
        WHEN invitee_status=3 THEN "declined" 
        WHEN invitee_status=0 THEN "notreviwed" END
    ) AS  invitee_status
     FROM your_tbl
    
    0 讨论(0)
提交回复
热议问题