您好我有这样的查询:
SELECT otel_id
FROM YAZILIM_menu_icerik
WHERE YAZILIM_menu_icerik.menu_id = 39
AND otel_id IN (
SELECT otel_id
FROM YAZILIM_menu_icerik
WHERE menu_id =$id
ORDER BY RAND()
)
LIMIT 0,20
它应该每次随机显示20家酒店,但相反,我最终每次都得到同样的20家酒店。长话短RAND()
似乎不起作用,我似乎无法找到任何逻辑错误。
SELECT otel_id
FROM YAZILIM_menu_icerik
WHERE YAZILIM_menu_icerik.menu_id = 39
AND otel_id IN (
SELECT otel_id
FROM YAZILIM_menu_icerik
WHERE menu_id =$id
)
ORDER BY RAND()
LIMIT 0,20
答案 0 :(得分:8)
您的ORDER BY和LIMIT条款应该在一起:
SELECT otel_id
FROM YAZILIM_menu_icerik
WHERE YAZILIM_menu_icerik.menu_id = 39
AND otel_id IN
(
SELECT otel_id
FROM YAZILIM_menu_icerik
WHERE menu_id = $id
)
ORDER BY RAND()
LIMIT 20
在没有ORDER BY
子句的子查询中使用LIMIT
是没有意义的,因为在外部查询的结果中不一定保留排序。
答案 1 :(得分:4)
ORDER BY RAND()是不好的解决方案。您的索引将被忽略。具有大量数据的特别困难的情况。
如果您在id上有主键,则替代:
SELECT b1.* FROM Bugs AS b1 JOIN
(SELECT CEIL( RAND()* (SELECT MAX(id) FROM Bugs)) AS id) AS b2
WHERE b1.id >= b2.id ORDER BY b1.id LIMIT 1