程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> MYSQL數據庫 >> 關於MYSQL數據庫 >> 如何隨機選取n條記錄或者對記錄作隨機排序?

如何隨機選取n條記錄或者對記錄作隨機排序?

編輯:關於MYSQL數據庫
. 如何得到隨機排序結果?

A. 要得到隨機排序的列,或者返回x條隨機選擇的列,你可以使用隨機數。但是RAND函數在一個查詢中只能返回一個結果。你可以在NOWID函數返回的列上做ORDER BY。請看示例:

SELECT *
FROM Northwind..Orders
ORDER BY NEWID()

SELECT TOP 10 *
FROM Northwind..Orders
ORDER BY NEWID()

這段話翻譯得真是費勁,干脆不管原文,直接意譯了。
不過提醒大家注意,這種方法是要對整個表掃描,然後產生一個計算列再排序的,最好不要對大的表作這樣的操作,否則會很慢的。


Q. How can I randomly sort query results?

A. To randomly order rows, or to return x number of randomly chosen rows, you can use the RAND function inside the SELECT statement. But the RAND function is resolved only once for the entire query, so every row will get same value. You can use an ORDER BY clause to sort the rows by the result from the NEWID function, as the following code shows:

SELECT *
FROM Northwind..Orders
ORDER BY NEWID()

SELECT TOP 10 *
FROM Northwind..Orders
ORDER BY NEWID()


—SQL Server MVPs

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved