Is it possible to divide records in both ascending and descending order in MySQL and display them alternatively?

MySQLMySQLi Database

Yes, you can perform this in MySQL by first getting the middle value. Let us first create a table:

mysql> create table DemoTable
(
   UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY
);
Query OK, 0 rows affected (0.65 sec)

Following is the query to insert some records in the table using insert command:

mysql> insert into DemoTable values();
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.06 sec)
mysql> insert into DemoTable values();
Query OK, 1 row affected (0.10 sec)

Following is the query to display records from the table using select command:

mysql> select *from DemoTable;

This will produce the following output

+--------+
| UserId |
+--------+
|      1 |
|      2 |
|      3 |
|      4 |
|      5 |
|      6 |
|      7 |
|      8 |
|      9 |
|     10 |
+--------+
10 rows in set (0.00 sec)

Here is the query to get the middle value first:

mysql> set @middleValue=(select max(UserId) from DemoTable)/2;
Query OK, 0 rows affected (0.01 sec)

Now, let us get the ascending and descending order value alternatively:

mysql> select *from DemoTable ORDER BY (IF(UserId <@middleValue,@middleValue*2-
UserId,UserId-1)) DESC,UserId ASC;

This will produce the following output

+--------+
| UserId |
+--------+
|      1 |
|      10|
|      2 |
|      9 |
|      3 |
|      8 |
|      4 |
|      7 |
|      6 |
|      5 |
+--------+
10 rows in set (0.00 sec)
raja
Published on 26-Apr-2019 12:15:59
Advertisements