我有UPDATE
次查询来更改videos
表中所有id_video
的记录状态(状态= 1),其中thumbnail
的记录数为{{1} } {} thubmnails.status
为1的表。
查询有效,但由于缩略图表的大小,它的速度非常慢。关于如何提高此查询速度的任何建议?
UPDATE videos
SET videos.status = 1
WHERE videos.id_video IN (SELECT thumbnails.id_video
FROM thumbnails
WHERE thumbnails.status = 1
GROUP BY thumbnails.id_video
HAVING Count(thumbnails.id_thumbnail) = 10)
AND videos.status = 2;
在两个表格中都为id_video设置了索引。缩略图表的id_thumbnail。还有status
列的索引。
答案 0 :(得分:2)
我通过使您的查询更简单来删除IN子句
UPDATE videos v
SET v.status = 1
WHERE v.status = 2 AND (
SELECT COUNT(t.id_thumbnail)
FROM thumbnails t
WHERE t.id_video = v.id_video AND t.status = 1
) = 10;
视频v记录只有在状态为2时才会更新,而且如果视频ID为v且状态为1,则会有10个缩略图t。
答案 1 :(得分:0)
如果将IN
子句转换为JOIN
条件(如
UPDATE videos v
JOIN (SELECT thumbnails.id_video
FROM thumbnails
WHERE thumbnails.status = 1
GROUP BY thumbnails.id_video
HAVING Count(thumbnails.id_thumbnail) = 10) xxx
ON v.id_video = xxx.id_video
SET v.status = 1
WHERE v.status = 2;
答案 2 :(得分:0)
您也可以尝试使用EXISTS代替IN:
UPDATE videos
SET videos.status = 1
WHERE videos.status = 2
AND EXISTS (SELECT thumbnails.id_video
FROM thumbnails
WHERE thumbnails.status = 1
GROUP BY thumbnails.id_video
HAVING Count(thumbnails.id_thumbnail) = 10
AND thumbnails.id_video = videos.id_video);