【问题标题】:MySQL order of executionMySQL执行顺序
【发布时间】:2019-07-11 16:06:39
【问题描述】:

我正在运行一个很长的查询,如下所述。 它为自动化系统上的每个帐户获取下一个所需的操作。

SELECT Account.id, 
(IFNULL(**Should send message query**, 
    IFNULL(**Should check inbox**, NULL))) as nextTask FROM Account

实际上 IFNULL 的字符串大约有 10 个,每个都是相当复杂的子查询。

我想知道如果第一个满足,MySQL 是否会计算下面的 IFNULL 表达式的值。也就是说,如果一个帐户应该发送一条消息,它不应该费心计算 应该检查收件箱

的子查询

这就是 MySQL 的工作原理吗?

这个和CASE WHEN's有什么区别

例如

CASE WHEN **Should send message** THEN **Should send message**
    WHEN **Should check inbox** THEN **Should check inbox**
END

我只想降低此查询的 CPU 使用率。

【问题讨论】:

  • 首先:使用COALESCE()
  • @PaulSpiegel,怎么样?这种情况有什么不同?
  • “有什么区别”? - 它更短。它符合 SQL 标准。

标签: mysql sql performance subquery


【解决方案1】:

你正在尝试的最好使用COALESCE(value,...)

返回列表中的第一个非 NULL 值,如果没有则返回 NULL 非 NULL 值。

原来是这样:

SELECT
    Account.id, 
    COALESCE(
        **Should send message query**, 
        **Should check inbox**
    ) as nextTask
FROM Account

现在回答你的实际问题

我想知道 MySQL 是否会计算以下 [IFNULL] 的值 如果满足第一个则表达式。

引擎没有理由这样做。您可以使用以下脚本对其进行测试:

set @executed1 = 'no';
set @executed2 = 'no';

select coalesce(
  @executed1 := 'yes', -- evaluates to non null
  @executed2 := 'yes'
);

select @executed1, @executed2;

结果:

@executed1 | @executed2
yes        | no

如您所见,第二个表达式未执行,因为第一个表达式已被评估为非 NULL 值。

set @executed1 = 'no';
set @executed2 = 'no';

select coalesce(
  nullif(@executed1 := 'yes', 'yes'), -- evaluates to null
  @executed2 := 'yes'
);

select @executed1, @executed2;

结果:

@executed1 | @executed2
yes        | yes

这里两个表达式都已执行,因为第一个表达式已被评估为 NULL。

db-fiddle

我会说 - IFNULL 也是如此。但我不会使用它。至少在你的情况下不是。

【讨论】:

    猜你喜欢
    • 2012-05-28
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 2023-03-27
    • 2018-02-06
    • 2014-03-05
    • 1970-01-01
    • 2011-03-28
    相关资源
    最近更新 更多