Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Order MySQL query by multiple ids?
For this, use ORDER BY FIELD(). Let us first create a table −
mysql> create table DemoTable( ClientId varchar(40), ClientName varchar(40) ); Query OK, 0 rows affected (0.55 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('987_John','John');
Query OK, 1 row affected (0.33 sec)
mysql> insert into DemoTable values('1000_Sam','Sam');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable values('777_Carol','Carol');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('2000_Bob','Bob');
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+-----------+------------+ | ClientId | ClientName | +-----------+------------+ | 987_John | John | | 1000_Sam | Sam | | 777_Carol | Carol | | 2000_Bob | Bob | +-----------+------------+ 4 rows in set (0.00 sec)
Following is the query to order MySQL query by multiple ids −
mysql> select *from DemoTable order by field(ClientId,'1000_Sam','2000_Bob','777_Carol','987_John');
This will produce the following output −
+-----------+------------+ | ClientId | ClientName | +-----------+------------+ | 1000_Sam | Sam | | 2000_Bob | Bob | | 777_Carol | Carol | | 987_John | John | +-----------+------------+ 4 rows in set (0.04 sec)
Advertisements
