![]() ![]() The following query returns a random customer from the customers table. Using this technique, you must execute the query multiple times to get more than one random row because if you increase the limit, the query will only give you sequential rows that start from the randomly selected row. ( SELECT MAX( id) FROM table_NAME )) AS id We can join the table with the result set returned by the above query as follows: SELECT t.* ![]() The following query generates a random number based on the primary key column: SELECT ROUND( RAND() * ( SELECT MAX( id) FROM table_name)) AS id Code language: SQL (Structured Query Language) ( sql ) This technique requires that the table has an auto-increment primary key field and there is no gap in the sequence. MySQL select random records using INNER JOIN clause The more rows the table has, the more time it takes to generate the random number for each row. The speed of the query also depends on the number of rows in the table. However, it will be slow for the big table because MySQL has to sort the entire table to select the random ones. ![]() This technique works very well with a small table. Notice that you may get a different result set because it is random. The following example selects five random customers from the customers table: SELECTĬode language: SQL (Structured Query Language) ( sql ) See the following customers table from the sample database. LIMIT N Code language: SQL (Structured Query Language) ( sql ) If you want to select N random records from a database table, you need to change the LIMIT clause as follows: SELECT * FROM table_name
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |