ORDER BY rand() and keep them grouped in MySQL?

CsharpServer Side ProgrammingProgramming

<p>Let us first create a table &minus;</p><pre class="result notranslate">mysql&gt; create table DemoTable &nbsp; &nbsp;-&gt; ( &nbsp; &nbsp;-&gt; StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, &nbsp; &nbsp;-&gt; StudentMarks int &nbsp; &nbsp;-&gt; ); Query OK, 0 rows affected (0.58 sec)</pre><p>Insert some records in the table using insert command. We have also inserted duplicate records &minus;</p><pre class="result notranslate">mysql&gt; insert into DemoTable(StudentMarks) values(98); Query OK, 1 row affected (0.11 sec) mysql&gt; insert into DemoTable(StudentMarks) values(98); Query OK, 1 row affected (0.10 sec) mysql&gt; insert into DemoTable(StudentMarks) values(78); Query OK, 1 row affected (0.10 sec) mysql&gt; insert into DemoTable(StudentMarks) values(78); Query OK, 1 row affected (0.29 sec) mysql&gt; insert into DemoTable(StudentMarks) values(45); Query OK, 1 row affected (0.10 sec) mysql&gt; insert into DemoTable(StudentMarks) values(56); Query OK, 1 row affected (0.09 sec)</pre><p>Display all records from the table using select statement &minus;</p><pre class="result notranslate">mysql&gt; select *from DemoTable;</pre><p>This will produce the following output &minus;</p><pre class="result notranslate">+-----------+--------------+ | StudentId | StudentMarks | +-----------+--------------+ | 1 &nbsp; &nbsp; &nbsp; &nbsp; | 98 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | | 2 &nbsp; &nbsp; &nbsp; &nbsp; | 98 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | | 3 &nbsp; &nbsp; &nbsp; &nbsp; | 78 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | | 4 &nbsp; &nbsp; &nbsp; &nbsp; | 78 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | | 5 &nbsp; &nbsp; &nbsp; &nbsp; | 45 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | | 6 &nbsp; &nbsp; &nbsp; &nbsp; | 56 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | +-----------+--------------+ 6 rows in set (0.00 sec)</pre><p>Following is the query to order by rand() keeping them grouped &minus;</p><pre class="result notranslate">mysql&gt; select *from DemoTable order by rand(StudentMarks*100*RAND());</pre><p>This will produce the following output. Here, the marks 98 records remain grouped &minus;</p><pre class="result notranslate" style="">+-----------+--------------+ | StudentId | StudentMarks | +-----------+--------------+ | 3 &nbsp; &nbsp; &nbsp; &nbsp; | 78 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | | 6 &nbsp; &nbsp; &nbsp; &nbsp; | 56 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | | 5 &nbsp; &nbsp; &nbsp; &nbsp; | 45 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | | 4 &nbsp; &nbsp; &nbsp; &nbsp; | 78 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | | 1 &nbsp; &nbsp; &nbsp; &nbsp; | 98 &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; | | 2 &nbsp; &nbsp; &nbsp; | 98 | +-----------+--------------+ 6 rows in set (0.00 sec)</pre>
raja
Updated on 11-Dec-2019 11:48:38

Advertisements