Home>Article>PHP Framework> laravel randomly extracts n pieces of data from mysql database (high performance)

laravel randomly extracts n pieces of data from mysql database (high performance)

藏色散人
藏色散人 forward
2020-07-03 11:54:50 3780browse

The following tutorial column fromLaravelwill 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!

laravel randomly extracts n pieces of data from mysql database (high performance)

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 theMysqlofficial website, you canORDER BY RAND ()Used together withLIMIT, 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 useDB::raw('RAND()')to get random data from the database. At the same time, you can also useorderByRaw('RAND()')to randomly obtain data from the database, which has the same effect asDB::raw('RAND()')

$info=self::where('dealing','<>','') ->orderBy(DB::raw('RAND()')) ->take(5) ->get();

3. Use laravel's inRandomOrder method to randomly obtain data

laravel usesinRandomOrderto 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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete
Previous article:What is a Blade template? Next article:What is a Blade template?