要查询值列表,可以使用IN运算符。语法如下-
SELECT * FROM yourTableName WHERE yourColumnName IN(Value1,Value2,...N) ORDER BY FIELD(yourColumnName,Value1,Value2,...N);
为了理解上述语法,让我们创建一个表。创建表的查询如下-
mysql> create table ListOfValues -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name varchar(30), -> Age int, -> PRIMARY KEY(Id) -> );
使用insert命令在表中插入一些记录。查询如下-
mysql> insert into ListOfValues(Name,Age) values('Carol',23); mysql> insert into ListOfValues(Name,Age) values('Bob',25); mysql> insert into ListOfValues(Name,Age) values('Sam',26); mysql> insert into ListOfValues(Name,Age) values('John',20); mysql> insert into ListOfValues(Name,Age) values('Mike',28); mysql> insert into ListOfValues(Name,Age) values('David',27); mysql> insert into ListOfValues(Name,Age) values('Larry',21);
现在,您可以使用select语句显示表中的所有记录。查询如下-
mysql> select *from ListOfValues;
以下是输出-
+----+-------+------+ | 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)
这是根据“年龄”列获取值列表的查询。查询如下-
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);
以下是输出。
+----+-------+------+ | 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)