条件为假时是否执行子查询?
Is a sub-query executed when the condition is false?
我有这个查询:
select *,
case when p.amount is null then '1'
else (select count(1)
from Money_paid mp
where mp.post_id = p.id and mp.user_id = :user_id limit 1)
end paid
from Posts p
where p.id = :post_id
如您所见,case .. when
函数的else
部分有一个子查询。现在我想知道,当 p.amount is null
为 true
时,该子查询会执行吗?
我问的是因为我可以通过 PHP 代码实现 case .. when
功能并将其从我的查询中删除,所以我的查询将是这样的:
select *,
(select count(1) from Money_paid mp
where mp.post_id = p.id and
mp.user_id = :user_id and
p.amount is not null
limit 1) paid
from Posts p
where p.id = :post_id
// and some php code to implement that condition
总而言之,如果该子查询针对两种情况(p.amount is null
= true
和 p.amount is null
= false
)执行,那么我将进行第二个查询(没有case .. when
)。但是当条件为 false
时子查询 仅 执行,那么我将使用第一个查询。
那是哪一个?
No ,除非没有其他条件为真,否则不会执行 ELSE
。
CASE EXPRESSION
正在按照您提出的顺序逐一评估他的所有条件,因此当满足第一个条件时,案例就会中断。
A CASE expression evaluates to the first true condition.
If there is no true condition, it evaluates to the ELSE part.
If there is no true condition and no ELSE part, it evaluates to NULL.
我有这个查询:
select *,
case when p.amount is null then '1'
else (select count(1)
from Money_paid mp
where mp.post_id = p.id and mp.user_id = :user_id limit 1)
end paid
from Posts p
where p.id = :post_id
如您所见,case .. when
函数的else
部分有一个子查询。现在我想知道,当 p.amount is null
为 true
时,该子查询会执行吗?
我问的是因为我可以通过 PHP 代码实现 case .. when
功能并将其从我的查询中删除,所以我的查询将是这样的:
select *,
(select count(1) from Money_paid mp
where mp.post_id = p.id and
mp.user_id = :user_id and
p.amount is not null
limit 1) paid
from Posts p
where p.id = :post_id
// and some php code to implement that condition
总而言之,如果该子查询针对两种情况(p.amount is null
= true
和 p.amount is null
= false
)执行,那么我将进行第二个查询(没有case .. when
)。但是当条件为 false
时子查询 仅 执行,那么我将使用第一个查询。
那是哪一个?
No ,除非没有其他条件为真,否则不会执行 ELSE
。
CASE EXPRESSION
正在按照您提出的顺序逐一评估他的所有条件,因此当满足第一个条件时,案例就会中断。
A CASE expression evaluates to the first true condition.
If there is no true condition, it evaluates to the ELSE part.
If there is no true condition and no ELSE part, it evaluates to NULL.