Home  >  Article  >  Backend Development  >  How to randomly select n records or randomly sort the records? _PHP Tutorial

How to randomly select n records or randomly sort the records? _PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 17:01:26797browse

Q. How to get randomly sorted results?
A. To get randomly sorted columns, or to return x randomly selected columns, you can use random numbers. But the RAND function can only return one result in a query. You can do ORDER BY on the column returned by the NOWID function. Please see the example:
SELECT *
FROM Northwind..Orders
ORDER BY NEWID()
SELECT TOP 10 *
FROM Northwind..Orders
ORDER BY NEWID()
It was really difficult to translate this passage, so I just ignored the original text and just translated it directly.
However, I would like to remind everyone that this method requires scanning the entire table, then generating a calculated column and then sorting it. It is best not to do such an operation on a large table, otherwise it will be very slow.
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

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/631149.htmlTechArticleQ. How to get randomly sorted results? A. To get randomly sorted columns, or return x randomly selected columns Column, you can use random numbers. But the RAND function can only return one in a query...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn