MySQL 查询一系列值?
为了查询一系列值,你可以使用 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) -> ); Query OK, 0 rows affected (0.72 sec)
使用 insert 命令在表中插入一些记录。查询如下 −
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)
现在你可以使用 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)
以下是对 Age 列进行值列表查询。查询如下 −
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)
广告