将子查询分离到其自己的 SELECT 语句中

发布于 2024-11-14 13:55:06 字数 564 浏览 1 评论 0原文

我正在处理一些旧代码(不是我的),我需要优化以下查询,因为它需要很长时间才能完成。我的猜测是子查询导致了它,

UPDATE topic a, cycle c
SET a.cycleId = c.id
WHERE a.id = 1
AND ((c.year * 100) + c.sequence) = (
                SELECT MIN((`year` * 100) + sequence)
                FROM cycle c2
                WHERE c2.groupId = a.groupId)

我正在考虑在更新语句之前在单独的查询中选择cycleId(c.id),但我在分离它时遇到了问题。到目前为止,我有以下内容,但我还没有考虑到 (c.year * 100) + c.sequence) 并且必须说实话,我不确定它在做什么!

SELECT c.id
FROM cycle c
LEFT JOIN topic a ON c.groupId = a.groupId
WHERE a.id = 1;

I'm working through some old code (not mine) and I need to optimise the following query because it is taking a long time to complete. My guess is the subquery is causing it

UPDATE topic a, cycle c
SET a.cycleId = c.id
WHERE a.id = 1
AND ((c.year * 100) + c.sequence) = (
                SELECT MIN((`year` * 100) + sequence)
                FROM cycle c2
                WHERE c2.groupId = a.groupId)

I was thinking of selecting the cycleId (c.id) in a separate query before the update statement but I am having problems separating it. So far I have the following but I haven't accounted for the (c.year * 100) + c.sequence) and have to be honest I'm not sure what that is doing!

SELECT c.id
FROM cycle c
LEFT JOIN topic a ON c.groupId = a.groupId
WHERE a.id = 1;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冷弦 2024-11-21 13:55:06

这是我暂时的解决方法。从以下位置获取结果:

SELECT MIN((`year` * 100) + sequence)
FROM cycle c
INNER JOIN topic a ON c.groupId = a.groupId
WHERE a.id = 1;

并在主查询中使用:

UPDATE topic a, cycle c
SET a.cycleId = c.id
WHERE a.id = 1
AND ((c.year * 100) + c.sequence) = [result]

This is my workaround for time being. Get the result from:

SELECT MIN((`year` * 100) + sequence)
FROM cycle c
INNER JOIN topic a ON c.groupId = a.groupId
WHERE a.id = 1;

and use in the main query:

UPDATE topic a, cycle c
SET a.cycleId = c.id
WHERE a.id = 1
AND ((c.year * 100) + c.sequence) = [result]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文