首页 > 数据库 > 从MySQL表中随机读取数据

从MySQL表中随机读取数据

2010年01月13号
查看评论 发表评论 294次浏览

如果用PHP的实现随机,但取出多条好像要进行两次以上查询.

翻了手册,找到了下面这个语句,可以完成任务了

SELECT * FROM table_name ORDER BY rand() LIMIT 5;

rand在手册里是这么说的:
RAND()
RAND(N)
返回在范围0到1.0内的随机浮点值。如果一个整数参数N被指定,它被用作种子值。
mysql> select RAND();
        -> 0.5925
mysql> select RAND(20);
        -> 0.1811
mysql> select RAND(20);
        -> 0.1811
mysql> select RAND();
        -> 0.2079
mysql> select RAND();
        -> 0.7888
你不能在一个ORDER BY子句用RAND()值使用列,因为ORDER BY将重复计算列多次。然而在MySQL3.23中,你可以做: SELECT * FROM table_name ORDER BY RAND(),这是有利于得到一个来自SELECT * FROM table1,table2 WHERE a=b AND c<d ORDER BY RAND() LIMIT 1000的集合的随机样本。注意在一个WHERE子句里的一个RAND()将在每次WHERE被执行时重新评估。

但我试了一下,8千条记录的表,执行一次需要0.08 sec,.慢了些

后来请教了google,得到如下代码

SELECT *
FROM table_name AS r1 JOIN
       (SELECT ROUND(RAND() *
                     (SELECT MAX(id)
                        FROM table_name)) AS id)
        AS r2
WHERE r1.id >= r2.id
ORDER BY r1.id ASC
LIMIT 5;

执行效率需要0.02 sec.可惜的是,只有mysql 4.1.*以上才支持这样的子查询.

类别数据库 标签
  1. mbt discount
    发表于 2010年06月14号 21时35分07秒 | 1楼

    What a beautiful creation

  2. cheap lacoste shoes
    发表于 2010年06月17号 10时59分20秒 | 2楼

    I just watched this, and thought it was really beautiful.

  3. air max trainers
    发表于 2010年06月23号 11时08分22秒 | 3楼

    Whoop whoop. I have a feeling this is becoming the best.Keep it up!:)

  4. Mbt Shoes
    发表于 2010年06月27号 01时25分47秒 | 4楼

    thanks for sharing your experience .. your Quest sounds amazing

  5. mbt shoes on sale
    发表于 2010年06月27号 04时31分24秒 | 5楼

    ya ya yooooooooo…. freshness

  6. lacoste t-shirts
    发表于 2010年07月02号 20时02分01秒 | 6楼

    I agree with most of this article

  7. ghd iv styler
    发表于 2010年07月19号 17时48分11秒 | 7楼

    This is a fine example.

  8. Hermes Handbags
    发表于 2010年07月19号 19时17分50秒 | 8楼

    Thank you.I liked these words:

  9. kobe shoes
    发表于 2010年07月19号 20时43分04秒 | 9楼

    That’s just what I needed to read today, thank you :)

  10. louboutin sale
    发表于 2010年07月20号 08时57分55秒 | 10楼

    I m so happy for your (mini)victory..you did it!!

  11. puma shoes sale
    发表于 2010年07月23号 09时49分14秒 | 11楼

    very inspirational and has had a deep impact to me and my emotions

  12. Ed Hardy swimwear
    发表于 2010年07月25号 15时51分43秒 | 12楼

    wow! Thank you for inspiring the heart of a writer within us.

  13. mbt lami
    发表于 2010年07月28号 16时55分26秒 | 13楼

    i feel you . you seem like a very warmn guy. thank you

  14. lebron shoes
    发表于 2010年07月29号 11时43分44秒 | 14楼

    Mmmm just what I need now.