[英]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. 我的查询是当我使用cubbersId搜索时,如果我得到
where cubbersId = 0
空数据where cubbersId = 0
否则where cubbersId = 1 (my_search_data)
类似于存储过程。
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
. 我搜索
cubbersId = 1
所以我得到了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. 但是我尝试搜索cubbersId = 2意味着cubbersId 2中
no data
,因此在这种情况下,我需要显示cubbersId = 0
数据。
this is my result: 这是我的结果:
where cubbersId = 1
datas: where cubbersId = 1
数据:
You can do it with UNION ALL. 您可以使用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)
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.