为此,请使用MySQL FIND_IN_SET()。让我们首先创建一个表-
mysql> create table DemoTable1563 -> ( -> StudentId int, -> StudentName varchar(20) -> );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1563 values(1001,'Chris'); mysql> insert into DemoTable1563 values(1010,'Bob'); mysql> insert into DemoTable1563 values(1005,'Chris'); mysql> insert into DemoTable1563 values(1015,'David'); mysql> insert into DemoTable1563 values(1030,'Mike'); mysql> insert into DemoTable1563 values(1020,'Sam');
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1563;
这将产生以下输出-
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1001 | Chris | | 1010 | Bob | | 1005 | Chris | | 1015 | David | | 1030 | Mike | | 1020 | Sam | +-----------+-------------+ 6 rows in set (0.00 sec)
这是形成与指定结果相同的MySQL结果集的查询-
mysql> select * from DemoTable1563 -> where StudentId IN(1001,1030,1010,1020) -> order by find_in_set(StudentId,'1001,1030,1010,1020');
这将产生以下输出-
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1001 | Chris | | 1030 | Mike | | 1010 | Bob | | 1020 | Sam | +-----------+-------------+ 4 rows in set (0.00 sec)