MySQL 查询从一列获取字符串,并使用逗号分隔值查找其在另一列中的位置?
mysqlmysqli database
为此,使用 FIND_IN_SET()。让我们首先创建一个表 −
mysql> create table DemoTable1866 ( Value1 int, ListOfValues varchar(100) ); Query OK, 0 rows affected (0.00 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable1866 values(56,'78,56,98,95'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1866 values(103,'103,90,102,104'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1866 values(77,'34,45,77,78'); Query OK, 1 row affected (0.00 sec)
使用 select 语句显示表中的所有记录 −
mysql> select * from DemoTable1866;
这将产生以下输出 −
+--------+----------------+ | Value1 | ListOfValues | +--------+----------------+ | 56 | 78,56,98,95 | | 103 | 103,90,102,104 | | 77 | 34,45,77,78 | +--------+----------------+ 3 rows in set (0.00 sec)
这是获取另一列中字符串位置的查询 −
mysql> select Value1,ListOfValues,find_in_set(Value1,ListOfValues) as Output from DemoTable1866;
这将产生以下输出 −
+--------+----------------+--------+ | Value1 | ListOfValues | Output | +--------+----------------+--------+ | 56 | 78,56,98,95 | 2 | | 103 | 103,90,102,104 | 1 | | 77 | 34,45,77,78 | 3 | +--------+----------------+--------+ 3 rows in set (0.00 sec)