简体   繁体   中英

How would I select the 1st, 12th, 68th or even 651st record with PHP?

Imagine I have a MySQL database table with 1,000 records in it and I wanted to select 1 record at random.

The records do not have an ID column where the numbers go up +1 each time. The ID numbers are randomly generated so the first records ID could be '932151540' and the second records ID could be '541577961'.

The only way I can think of selecting 1 record at random is by finding out how many records there are in total. Pick a random number between 1 and however many there are (say the random number was 467). Then getting the 467th record.

How would I do this using PHP?

Thanks in advance :)

SELECT * FROM table ORDER BY RAND() LIMIT 1;
SELECT *
FROM TABLE
ORDER BY RAND()
LIMIT 1

An alternative query you could use is

SELECT * FROM myTable WHERE RAND()<(SELECT ((1/COUNT(*))*10) FROM myTable) ORDER BY RAND() LIMIT 1; Which will yield much better performance as the size of your table increases.

To quote the author:

This method uses ORDER BY RAND(), but only on a small percentage of the table rows; this percentage is based upon how many rows you want, LIMIT 1, divided by how many rows the table has, COUNT(*), and then multiply that figure by 10 to avoid returning less rows than you request. I developed this method after reading How to select random rows in MySQL @ rndblog.com .

Read the full post here for a detailed explanation and performance analysis, along with other alternatives which are possibly not applicable in your case..

im using this instead of slow ORDER BY rand() , quite faster.

$table = "mytable";
$offset_result = mysql_query("SELECT FLOOR(RAND() * COUNT(*)) AS offset FROM ".$table.";");
$offset_row = mysql_fetch_object($offset_result);
$offset = $offset_row->offset;
$result = mysql_query("SELECT * FROM ".$table." LIMIT ".$offset.", 1;"); 
$result_row = mysql_fetch_row($result);  // point to record
$row = $result_row[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM