6

Hello I have a query like this:

    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

It should display randomly 20 hotels each time it works but instead , i'm ending up getting the same 20 hotel each time. Long story short RAND() doesn't seem to work and I can't seem to find any logical error.

EDIT: Problem solved. Mysql doesn't see inner RAND() so here's the correct way to do it:

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
1
  • 1
    ORDER BY RAND() is terribly inefficient - you should probably try and find another solution. Regardless, if you move the ORDER BY RAND() to outside the ), does it work?
    – Swadq
    Dec 10, 2012 at 8:49

2 Answers 2

9

Your ORDER BY and LIMIT clauses should be together:

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

It makes no sense to have a bare ORDER BY in a subquery with no LIMIT clause because the ordering is not necessarily preserved in the results of the outer query.

1
  • 2
    Problem solved 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";
    – FreshPro
    Dec 10, 2012 at 9:16
4

ORDER BY RAND() is bad solution. Your indexes are ignored. Particularly difficult situation with large amounts of data.

Alternative if you have primary key on 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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.