我目前正在开展一个需要"类似系列"面板。我有一个系列表和他们的一个类型。需要选择与所选电影共有至少4种类型的电影。
我提出了这个问题:
SELECT s_id,stitle,sdesc FROM s_genre
INNER JOIN series ON s_genre.s_id=series.id
WHERE s_id IN (
SELECT s_id FROM s_genre
INNER JOIN (SELECT g_id FROM s_genre WHERE s_id = $mid) a USING (g_id)
GROUP BY s_id HAVING COUNT(s_id)>3
) AND s_id != $mid
ORDER BY RAND()
LIMIT 5
它可以工作,但加载需要将近20秒:(
我有什么想法可以减少加载时间?任何建议表示赞赏:)
看起来问题是由" ORDER BY RAND()" ...删除它会将加载时间减少到0.5秒
答案 0 :(得分:1)
虽然ORDER BY rand()似乎是主要问题,但可能需要重新编码查询以对子查询进行连接: -
SELECT s_genre.s_id,
series.stitle,
series.sdesc
FROM s_genre
INNER JOIN series ON s_genre.s_id = series.id
INNER JOIN
(
SELECT a.s_id
FROM s_genre a
INNER JOIN s_genre b
ON a.g_id = b.g_id
WHERE b.s_id = $mid
GROUP BY a.s_id
HAVING COUNT(a.s_id) > 3
) sub0
ON s_genre.s_id = sub0.s_id
WHERE s_genre.s_id != $mid
ORDER BY RAND()
LIMIT 5
有一些技术可以选择随机记录,但使用此查询执行此操作可能会有点混乱。大多数都依赖于为行提供一个相当均匀分布的唯一标识符,并且(虽然我假设s_genre.s_id是一个唯一的id),查询将在这些范围内生成漏洞,它们无疑会在该范围内出现漏洞。