ランダムな行を取得したい HWC というテーブルがあり、データベースには約 10,000 のエントリがあり、以前使用していた方法は遅すぎました。
ここに私のクエリがあります:
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();
}