我有一个名为 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();
}