如何在mysql数据库中查询10个随机唯一记录?

时间:2012-08-23 08:20:26

标签: mysql

  

可能重复:
  how to select random unique records on each execution of the SQL Query

我有这个结构的数据库:

id int
image_name varchar(200)
category_id int

大约有200条记录,id是唯一的,大约有20个类别,我的iamges在它们之间进行分类。

你能帮我查询一下,这会给我带有UNIQUE category_ids的10条记录吗?

3 个答案:

答案 0 :(得分:7)

select DISTINCT(category),id,image_name FROM images 
  WHERE id=
    (FLOOR(RAND() * 
           (SELECT COUNT(*) FROM images )
          )
    );

答案 1 :(得分:2)

SELECT DISTINCT(category),id,image_name FROM images ORDER BY RAND() LIMIT 10

答案 2 :(得分:1)

SELECT DISTINCT category_id,id,image_name FROM images ORDER BY RAND() LIMIT 10