如何能够获得与在 MySQL WHERE 子句中使用循环一样的结果,只显示交替 ID 记录?
使用 MySQL IN() 获得类似结果。让我们首先创建一个表 -
mysql> create table DemoTable ( ClientId int, ClientName varchar(100), ClientAge int ); Query OK, 0 rows affected (0.70 sec)
使用 insert 命令向表中插入一些记录 -
mysql> insert into DemoTable values(100,'Chris',34); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values(101,'Robert',31); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable values(103,'David',33); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable values(104,'Mike',45); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable values(105,'Sam',39); Query OK, 1 row affected (0.09 sec)
使用 select 语句显示表中的所有记录 -
mysql> select *from DemoTable;
这将产生以下输出 -
+----------+------------+-----------+ | ClientId | ClientName | ClientAge | +----------+------------+-----------+ | 100 | Chris | 34 | | 101 | Robert | 31 | | 103 | David | 33 | | 104 | Mike | 45 | | 105 | Sam | 39 | +----------+------------+-----------+ 5 rows in set (0.00 sec)
以下是使用 MySQL IN() 获得与循环类似结果的查询 -
mysql> select ClientId,ClientName,ClientAge from DemoTable where ClientId IN(101,103,105);
这将产生以下输出 -
+----------+------------+-----------+ | ClientId | ClientName | ClientAge | +----------+------------+-----------+ | 101 | Robert | 31 | | 103 | David | 33 | | 105 | Sam | 39 | +----------+------------+-----------+ 3 rows in set (0.00 sec)
广告