如何使 MySQL 结果集与指定的内容相同?
对此,可以使用 MySQL FIND_IN_SET()。我们首先创建一个表 −
mysql> create table DemoTable1563 -> ( -> StudentId int, -> StudentName varchar(20) -> ); Query OK, 0 rows affected (0.52 sec)
使用插入命令向表中插入一些记录 −
mysql> insert into DemoTable1563 values(1001,'Chris'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable1563 values(1010,'Bob'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable1563 values(1005,'Chris'); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable1563 values(1015,'David'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable1563 values(1030,'Mike'); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1563 values(1020,'Sam'); Query OK, 1 row affected (0.14 sec)
使用 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)
广告