MySQL查询从一列中获取字符串,并用逗号分隔的值在另一列中找到其位置?

为此,请使用FIND_IN_SET()。让我们首先创建一个表-

mysql> create table DemoTable1866
     (
     Value1 int,
     ListOfValues varchar(100)
     );

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable1866 values(56,'78,56,98,95');
mysql> insert into DemoTable1866 values(103,'103,90,102,104');
mysql> insert into DemoTable1866 values(77,'34,45,77,78');

使用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)