如何按 IN 子句的顺序选择 MySQL 行?
mysqlmysqli database
您需要使用 FIND_IN_SET() 函数按 IN 子句的顺序选择 MySQL 行。语法如下 −
SELECT yourVariableName.* FROM yourTableName yourVariableName WHERE yourVariableName.yourColumnName IN(value1,value2,...N) ORDER BY FIND_IN_SET( yourVariableName.yourColumnName,'value1,value2,...N');
为了理解上述语法,让我们创建一个表。创建表的查询如下 −
mysql> create table InDemo -> ( -> CodeId int, -> Name varchar(20) -> ); Query OK, 0 rows affected (0.95 sec)
使用 insert 命令在表中插入一些记录。 查询语句如下 −
mysql> insert into InDemo values(1,'John'); Query OK, 1 row affected (0.24 sec) mysql> insert into InDemo values(2,'Carol'); Query OK, 1 row affected (0.19 sec) mysql> insert into InDemo values(3,'Sam'); Query OK, 1 row affected (0.18 sec) mysql> insert into InDemo values(4,'Bob'); Query OK, 1 row affected (0.17 sec)
现在,您可以使用 select 语句显示表中的所有记录。查询如下 −
mysql> select *from InDemo;
以下是输出 −
+--------+-------+ | CodeId | Name | +--------+-------+ | 1 | John | | 2 | Carol | | 3 | Sam | | 4 | Bob | +--------+-------+ 4 rows in set (0.00 sec)
这是按 IN 子句顺序选择 MySQL 行的查询 −
mysql> select tbl.* -> from InDemo tbl -> where tbl.CodeId in(1,3,2,4) -> ORDER BY FIND_IN_SET( tbl.CodeId,'1,3,2,4');
以下是输出 −
+--------+-------+ | CodeId | Name | +--------+-------+ | 1 | John | | 3 | Sam | | 2 | Carol | | 4 | Bob | +--------+-------+ 4 rows in set (0.00 sec)