gpt4 book ai didi

mysql - 优化mysql子查询执行时间

转载 作者:行者123 更新时间:2023-11-30 21:25:22 25 4
gpt4 key购买 nike

我有以下问题:

select
qs.*
from
(
select
tsk.id,
tsk.request_id,
tsk.hash_id
from
user_tasks as usr
inner join unassigned_tasks as tsk on usr.task_id = tsk.id
where
usr.assigned_to = 53
AND tsk.product_id NOT IN (
SELECT
product_id
FROM
product_progresses
WHERE
request_id = tsk.request_id
)
ORDER BY
tsk.id
) as qs <-- this takes about 233ms.
WHERE
qs.id = ( <-- should this subquery execute for every row from outer result-set row?
SELECT
min(qt.id)
FROM
(
select
tsk.id,
tsk.request_id,
tsk.hash_id
from
user_tasks as usr
inner join unassigned_tasks as tsk on usr.task_id = tsk.id
where
usr.assigned_to = 53
AND tsk.product_id NOT IN (
SELECT
product_id
FROM
product_progresses
WHERE
request_id = tsk.request_id
)
ORDER BY
tsk.id
) as qt <-- this takes about 233ms.
WHERE
qt.id > 83934
)

qsqt 的执行时间差不多,即大约 233ms

此外,执行整个查询大约需要相同的时间。

我有一个概念,where qs.id = (...) 中的内部查询对 qs 生成的结果集中的每一行执行一次。

在当前这种情况下,qs 输出 10 行。

所以我决定测试子查询是否对每一行都执行了10次。

这是我放在子查询中的内容:

WHERE qs.id = (
SELECT
SLEEP(1)
)

而不是 where qs.id = ( select min(qt.id) ... )

这花费了大约 10.246 秒,这证明正在为每一行运行内部查询。

因此,初始查询不应该花费大约 (qt time) 233 * 10 (rows from qs) = 2330ms 吗?

是因为select min()..只计算了一次吗?

最佳答案

在 MySQL 中,FROM 子句中的子查询在 WHERE 子句中的子查询之前求值。

有用的文章: https://www.eversql.com/sql-order-of-operations-sql-query-order-of-execution/

在您的情况下,这导致 qsWHERE 子句被考虑在内之前被完全评估。如果您希望 qsqt 限制,您应该能够通过取消嵌套 qs 或将 qt 移动到 qs 中来实现。

但在实践中,与其对 WHERE 子句使用子查询,不如使用连接可能更好。

参见 SQL select only rows with max value on a column

关于mysql - 优化mysql子查询执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59354086/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com