php - 条件为假时是否执行子查询?

标签 php mysql subquery

我有这个问题:

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 为 nulltrue 时,该子查询会执行吗?


我这样问是因为我可以通过 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/

相关文章:

php - 如何将额外数据存储到多 curl 信息处理程序中?

php - 多个mysql查询到一个php二维数组

PHP:序列化对象并将它们粘贴到数据库中以备后用是不是糟糕的设计?

mysql - 在另一个存储过程中使用mysql存储过程的结果集

mysql - 获得最高分并在您之后的下一个和上一个得分 3

SQL:使用冗余联合代码优化嵌套查询?

mysql - 分组后选择中的子查询

javascript - 从数据库填充下拉框而不重新加载页面

mysql - 短路 SQL 以返回找到的第一个 X 行

mysql - 在第 1 行的 CSV 输入中出现无效的列计数错误