To query a list of values, you can use IN operator. The syntax is as follows −
SELECT * FROM yourTableName WHERE yourColumnName IN(Value1,Value2,...N) ORDER BY FIELD(yourColumnName,Value1,Value2,...N);
To understand the above syntax, let us create a table. The query to create a table is as follows −
mysql> create table ListOfValues -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name varchar(30), -> Age int, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.72 sec)
Insert some records in the table using insert command. The query is as follows −
mysql> insert into ListOfValues(Name,Age) values('Carol',23); Query OK, 1 row affected (0.14 sec) mysql> insert into ListOfValues(Name,Age) values('Bob',25); Query OK, 1 row affected (0.17 sec) mysql> insert into ListOfValues(Name,Age) values('Sam',26); Query OK, 1 row affected (0.16 sec) mysql> insert into ListOfValues(Name,Age) values('John',20); Query OK, 1 row affected (0.37 sec) mysql> insert into ListOfValues(Name,Age) values('Mike',28); Query OK, 1 row affected (0.13 sec) mysql> insert into ListOfValues(Name,Age) values('David',27); Query OK, 1 row affected (0.21 sec) mysql> insert into ListOfValues(Name,Age) values('Larry',21); Query OK, 1 row affected (0.20 sec)
Now you can display all records from the table using a select statement. The query is as follows −
mysql> select *from ListOfValues;
The following is the output −
+----+-------+------+ | Id | Name | Age | +----+-------+------+ | 1 | Carol | 23 | | 2 | Bob | 25 | | 3 | Sam | 26 | | 4 | John | 20 | | 5 | Mike | 28 | | 6 | David | 27 | | 7 | Larry | 21 | +----+-------+------+ 7 rows in set (0.00 sec)
Here is the query to get the list of values on the basis of the Age column. The query is as follows −
mysql> select *from ListOfValues where Age IN(20,21,23,25,26,27,28) -> order by field(Age,20,21,23,25,26,27,28);
The following is the output.
+----+-------+------+ | Id | Name | Age | +----+-------+------+ | 4 | John | 20 | | 7 | Larry | 21 | | 1 | Carol | 23 | | 2 | Bob | 25 | | 3 | Sam | 26 | | 6 | David | 27 | | 5 | Mike | 28 | +----+-------+------+ 7 rows in set (0.06 sec)