Chinaunix首页 | 论坛 | 博客
  • 博客访问: 248391
  • 博文数量: 14
  • 博客积分: 2015
  • 博客等级: 大尉
  • 技术积分: 902
  • 用 户 组: 普通用户
  • 注册时间: 2006-10-27 16:02
文章分类

全部博文(14)

文章存档

2009年(5)

2008年(9)

我的朋友

分类: LINUX

2008-07-28 17:07:52

There are lots of ways to select a random record or row from a database table. Here are some example SQL statements that don't require additional application logic, but each database server requires different SQL syntax.

Select a random row with MySQL:

SELECT column FROM table
ORDER BY RAND()
LIMIT 1

Select a random row with PostgreSQL:

SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1

Select a random row with Microsoft SQL Server:

SELECT TOP 1 column FROM table
ORDER BY NEWID()

Select a random row with IBM DB2

SELECT column, RAND() as IDX
FROM table
ORDER BY IDX FETCH FIRST 1 ROWS ONLY

Thanks

Select a random record with Oracle:

SELECT column FROM
( SELECT column FROM table
ORDER BY dbms_random.value )
WHERE rownum = 1

Thanks Mark Murphy

Feel free to post other example, variations, and SQL statements for other database servers in the comments.

阅读(1240) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~