在LEFT OUTER JOIN中优化MySQL的ORDER BY RAND()函数

时间:2014-08-11 11:10:27

标签: mysql sql random

我想优化我的查询。这个查询对我的服务器来说太慢了。

这个问题有什么解决方案吗? 谢谢!

SELECT *,TABLE.id AS identyfikator 
FROM TABLE 
LEFT OUTER JOIN TABLE_TWO ON TABLE.code = TABLE_TWO.code 
WHERE TABLE_TWO.city = $ID 
ORDER BY RAND() LIMIT 3

2 个答案:

答案 0 :(得分:0)

你可以将order by和limit分开,以便它可以快速

SELECT * FROM (
    SELECT 
        *,
        TABLE.id AS identyfikator 
    FROM TABLE 
    LEFT OUTER JOIN TABLE_TWO ON TABLE.code = TABLE_TWO.code 
    WHERE TABLE_TWO.city = $ID 
) m 
ORDER BY RAND() LIMIT 3

答案 1 :(得分:0)

尝试在两个表的代码列上创建索引。