我有这个问题:
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 为 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
and 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.
关于php - 条件为假时是否执行子查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36597062/