-1

我有一个名为 HWC 的表,我想获得一个随机行,我的数据库有大约 10k 个条目,而我之前使用的方法太慢了。

这是我的查询:

SELECT *
FROM HWC AS r1 JOIN
   (SELECT (RAND() *
                 (SELECT MAX(id)
                    FROM HWC)) AS id)
    AS r2 WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 1

这是我在 PHP 中遇到的错误:

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* FROM HWC AS r1 JOIN (SELECT (RAND() * (SELECT MAX(id) FROM HWC)) AS id) A' at line 2

SELECT * FROM (`SELECT` * FROM HWC AS r1 JOIN (SELECT (RAND() * (SELECT MAX(id) FROM HWC)) AS id) AS r2 WHERE r1.id >= r2.id ORDER BY r1.id ASC LIMIT 1)

我的模型的完整 PHP 代码:

function random()
{
$query = "SELECT *
FROM HWC AS r1 JOIN
   (SELECT (RAND() *
                 (SELECT MAX(id)
                    FROM HWC)) AS id)
    AS r2 WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 1";
$result = $this->db->get($query);

return $result->result_array();
}
4

2 回答 2

1

我的 get() 应该是一个 query(); 现在工作完美而快速。

于 2013-06-08T23:46:38.727 回答
0

去掉第二个刻度SELECT

SELECT * FROM (SELECT * FROM HWC ...
于 2013-06-08T23:41:27.657 回答