MySQLÖÐÌá¸ßOrder By Rand()Ö´ÐÐЧÂʵÄÓÅ»¯·½·¨
×î½üÓÉÓÚÐèÒª´ó¸ÅÑо¿ÁËÒ»ÏÂMYSQLµÄËæ»ú³éȡʵÏÖ·½·¨¡£¾Ù¸öÀý×Ó£¬Òª´Ótablename±íÖÐËæ»úÌáÈ¡Ò»Ìõ¼Ç¼£¬´ó¼ÒÒ»°ãµÄд·¨¾ÍÊÇ£ºSELECT * FROM tablename ORDER BY RAND() LIMIT 1¡£
µ«ÊÇ£¬ºóÀ´ÎÒ²éÁËÒ»ÏÂMYSQLµÄ¹Ù·½ÊֲᣬÀïÃæÕë¶ÔRAND()µÄÌáʾ´ó¸ÅÒâ˼¾ÍÊÇ£¬ÔÚORDER BY´Ó¾äÀïÃæ²»ÄÜʹÓÃRAND()º¯Êý£¬ÒòΪÕâÑù»áµ¼ÖÂÊý¾ÝÁỶà´ÎɨÃè¡£µ«ÊÇÔÚMYSQL 3.23°æ±¾ÖУ¬ÈÔÈ»¿ÉÒÔͨ¹ýORDER BY RAND()À´ÊµÏÖËæ»ú¡£
µ«ÊÇÕæÕý²âÊÔһϲŷ¢ÏÖÕâÑùЧÂʷdz£µÍ¡£Ò»¸ö15ÍòÓàÌõµÄ¿â£¬²éѯ5ÌõÊý¾Ý£¬¾ÓȻҪ8ÃëÒÔÉÏ¡£²é¿´¹Ù·½ÊֲᣬҲ˵rand()·ÅÔÚORDER BY ×Ó¾äÖлᱻִÐжà´Î£¬×ÔȻЧÂʼ°ºÜµÍ¡£ You cannot use a column with RAND() values in an ORDER BY clause, because ORDER BY would evaluate the column multiple times.
ËÑË÷Google£¬ÍøÉÏ»ù±¾É϶¼ÊDzéѯmax(id) * rand()À´Ëæ»ú»ñÈ¡Êý¾Ý¡£
SELECT *
FROM `table` AS t1 JOIN (SELECT ROUND(RAND() * (SELECT MAX(id) FROM `table`)) AS id) AS t2
WHERE t1.id >= t2.id
ORDER BY t1.id ASC LIMIT 5;
µ«ÊÇÕâÑù»á²úÉúÁ¬ÐøµÄ5Ìõ¼Ç¼¡£½â¾ö°ì·¨Ö»ÄÜÊÇÿ´Î²éѯһÌõ£¬²éѯ5´Î¡£¼´±ãÈç´ËÒ²ÖµµÃ£¬ÒòΪ15ÍòÌõµÄ±í£¬²éѯֻÐèÒª0.01Ãë²»µ½¡£
ÏÂÃæµÄÓï¾ä²ÉÓõÄÊÇJOIN£¬mysqlµÄÂÛ̳ÉÏÓÐÈËʹÓÃ
SELECT *
FROM `table`
WHERE id >= (SELECT FLOOR( MAX(id) * RAND()) FROM `table` )
ORDER BY id LIMIT 1;
ÎÒ²âÊÔÁËһϣ¬ÐèÒª0.5Ã룬ËÙ¶ÈÒ²²»´í£¬µ«ÊǸúÉÏÃæµÄÓï¾ä»¹ÊÇÓкܴó²î¾à¡£×ܾõÓÐʲôµØ·½²»Õý³£¡£
ÓÚÊÇÎÒ°ÑÓï¾ä¸ÄдÁËһϡ£ SELECT * FROM `table`
WHERE id >= (SELECT floor(RAND() * (SELECT MAX(id) FROM `table`)))
ORDER BY id LIMIT 1;
ÕâÏ£¬Ð§ÂÊÓÖÌá¸ßÁË£¬²éѯʱ¼äÖ»ÓÐ0.01Ãë
×îºó£¬ÔÙ°ÑÓï¾äÍêÉÆһϣ¬¼ÓÉÏMIN(id)µÄÅжϡ£ÎÒÔÚ×ʼ²âÊÔµÄʱºò£¬¾ÍÊÇÒòΪûÓмÓÉÏMIN(id)µÄÅжϣ¬½á¹ûÓÐÒ»°ëµÄʱ¼ä×ÜÊDzéѯµ½±íÖеÄÇ°Ã漸ÐС£
ÍêÕû²éѯÓï¾äÊÇ£º
SELECT * FROM `table`
WHERE id >= (SELECT floor( RAND() * ((SELECT MAX(id) FROM `table`)-(SELECT MIN(id) FROM `table`)) + (SELECT MIN(id) FROM `table`)))
ORDER BY id LIMIT 1;
SELECT *
FROM `table` AS t1 JOIN (SELECT ROUND(RAND() * ((SELECT MAX(id) FROM `table`)-(SELECT MIN(id) FROM `table`))+(SELECT MIN(id) FROM `table`)) AS id) AS t2
WHERE t1.id >= t2.id
ORDER BY t1.id LIMIT 1;
×îºóÔÚphpÖжÔÕâÁ½¸öÓï¾ä½øÐзֱð²éѯ10´Î£¬
Ç°Õß»¨·Ñʱ¼ä 0.147433 Ãë
ºóÕß»¨·Ñʱ¼ä 0.015130 Ãë
¿´À´²ÉÓÃJOINµÄÓï·¨±ÈÖ±½ÓÔÚWHEREÖÐʹÓú¯ÊýЧÂÊ»¹Òª¸ßºÜ¶à¡£
ÍƼöÐÅÏ¢
ÈÈÃÅÐÅÏ¢
- nohup: redirecting stderr to stdou....
- ʹÓÃlog_formatΪNginx·þÎñÆ÷ÉèÖøüÏêϸµÄÈÕÖ¾¸ñʽ
- jquery easyUI--dataGrid-Json
- [Ô´´]·ÂGoogle Reader¡¢ÐÂÀË΢²©¡¢ÌÚѶ΢²©µ....
- ÀûÓÃKeepalived+mysql¹¹½¨¸ß¿ÉÓÃMySQLË«Ö÷×Ô¶....
- Nginx+keepalivedʵÏÖ¸ºÔؾùºâºÍË«»úÈȱ¸¸ß¿ÉÓÃ
- jqueryʵÏÖÒ³Ãæ¼ÓÔؽø¶ÈÌõ
- Rolling cURL: PHP²¢·¢×î¼Ñʵ¼ù
- codeigniter ·ÓÉÖÕ¼«ÓÅ»¯(url rewrite)
- linuxÏÂÉèÖÃsshÎÞÃÜÂëµÇ¼
ÆÀÂÛ