Home > Article > PHP Framework > laravel randomly extracts n pieces of data from mysql database (high performance)
The following tutorial column from Laravel will introduce to you how laravel randomly extracts n pieces of data from the mysql database. I hope it will be helpful to friends in need!
How does laravel randomly obtain n pieces of data from the mysql database with high performance? Sometimes we often need to randomly obtain data from the database, for example: randomly assign 10 to the staff order, randomly check 100 users from the database; in this way, we need to randomly obtain data from the database.
1. Use native SQL to obtain 100 pieces of data from the database
As you can see from the Mysql
official website, you can ORDER BY RAND ()
Used together with LIMIT
, can be used to select a random part from multiple rows of results.
SELECT * FROM table WHERE name="" ORDER BY RAND() LIMIT 100;
Then using native SQL in laravel is also very simple, as shown below:
$info = DB::select('SELECT * FROM table WHERE name="" ORDER BY RAND() LIMIT 100');
2. Use original expressions to randomly obtain data from the data
We all know the original expression of laravel, we can use DB::raw('RAND()')
to get random data from the database. At the same time, you can also use orderByRaw('RAND()')
to randomly obtain data from the database, which has the same effect as DB::raw('RAND()')
$info=self::where('dealing','<>','') ->orderBy(DB::raw('RAND()')) ->take(5) ->get();
3. Use laravel's inRandomOrder method to randomly obtain data
laravel uses inRandomOrder
to randomly sort the data results to achieve the goal of randomly obtaining data from the database. Effect:
$info = DB::table('users') ->inRandomOrder() ->take(5) ->get();
The above is the detailed content of laravel randomly extracts n pieces of data from mysql database (high performance). For more information, please follow other related articles on the PHP Chinese website!