简体   繁体   中英

MySql case condition in where clause

This is my table

在此处输入图片说明

My query is when I search using cubbersId, if i got empty data where cubbersId = 0 else where cubbersId = 1 (my_search_data) its like stored procedure.

I tried this query

SELECT * FROM hometestimonial WHERE (CASE 
    WHEN cubbersId IS NOT NULL THEN cubbersId = 1
    ELSE cubbersId = 0
END)

I search cubbersId = 1 so i got 3 datas . But i tried to search cubbersId = 2 means no data in cubbersId 2, so in this case i need to show cubbersId = 0 data's.

this is my result:

where cubbersId = 1 datas:

在此处输入图片说明

where cubbersId = 2 datas: 在此处输入图片说明

You can do it with UNION ALL.
The 2nd query will return rows only if the 1st is empty:

SELECT * FROM hometestimonial
WHERE cubbersId = 2
UNION ALL
SELECT * FROM hometestimonial
WHERE cubbersId = 0 AND 
NOT EXISTS (
  SELECT 1 FROM hometestimonial
  WHERE cubbersId = 2
)

If you want the result you should move the case in select

    SELECT *,  CASE 
        WHEN cubbersId IS NOT NULL THEN  1
        ELSE  0
    END my_cubbersId
    FROM hometestimonial 

Here is another alternative:

SELECT ht.*
FROM hometestimonial ht
WHERE ht.cubbersId = (SELECT MAX(h2.cubbersID)
                      FROM hometestimonial ht2
                      WHERE cubbersID IN (0, 2)
                     );

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