开发者

Separating out a subquery into its own SELECT statement

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 que开发者_如何学JAVAry 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;


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]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜