[英]using CASE in the WHERE clause
simplified version of my query 我的查询的简化版本
SELECT *
FROM logs
WHERE pw='correct' AND CASE WHEN id<800 THEN success=1 ELSE END
AND YEAR(timestamp)=2011
this doesn't work. 这不起作用。 What i'm trying to do is to add in success=1
only for rows with id<800
, else ignore this check. 我想要做的是仅为id<800
行添加success=1
,否则忽略此检查。
how do i write this? 我怎么写这个? thanks! 谢谢!
edit: to clarify, this what the table looks like 编辑:澄清,这是表格的样子
|id | pw | success |
--------------------------
|700 | correct | 1 |
|710 | correct | 1 |
|900 | correct | NULL |
|999 | correct | 0 |
I'm trying to return all the rows, the column pw
cannot be ignored. 我试图返回所有行,列pw
不能被忽略。
You don't have to use CASE...WHEN, you could use an OR condition, like this: 您不必使用CASE ... WHEN,您可以使用OR条件,如下所示:
WHERE
pw='correct'
AND (id>=800 OR success=1)
AND YEAR(timestamp)=2011
this means that if id<800, success has to be 1 for the condition to be evaluated as true. 这意味着如果id <800,则成功必须为1才能将条件评估为true。 Otherwise, it will be true anyway. 否则,无论如何都是如此。
It is less common, however you could still use CASE WHEN, like this: 它不太常见,但你仍然可以使用CASE WHEN,如下所示:
WHERE
pw='correct'
AND CASE WHEN id<800 THEN success=1 ELSE TRUE END
AND YEAR(timestamp)=2011
this means: return success=1
(which can be TRUE or FALSE) in case id<800, or always return TRUE otherwise. 这意味着:如果id <800,则返回success=1
(可以是TRUE或FALSE),否则返回TRUE。
SELECT *
FROM logs
WHERE pw='correct'
AND CASE
WHEN id<800 THEN success=1
ELSE 1=1
END
AND YEAR(TIMESTAMP)=2011
This is working Oracle example but it should work in MySQL too. 这是Oracle的一个例子,但它也适用于MySQL。
You are missing smth - see IN after END Replace 'IN' with '=' sign for a single value. 你缺少smth - 在END之后看到IN用'='替换'IN'代表单个值。
SELECT empno, ename, job
FROM scott.emp
WHERE (CASE WHEN job = 'MANAGER' THEN '1'
WHEN job = 'CLERK' THEN '2'
ELSE '0' END) IN (1, 2)
You can transform logical implication A => B
to NOT A or B
. 您可以将逻辑蕴涵A => B
为NOT A or B
This is one of the most basic laws of logic. 这是最基本的逻辑法则之一。 In your case it is something like this: 在你的情况下,它是这样的:
SELECT *
FROM logs
WHERE pw='correct' AND (id>=800 OR success=1)
AND YEAR(timestamp)=2011
I also transformed NOT id<800
to id>=800
, which is also pretty basic. 我还将NOT id<800
转换为id>=800
,这也是非常基本的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.