MySQL 查询用于从一个数组中提取匹配的特定的记录(逗号分隔的值)
要从逗号分隔的值中提取记录,请使用 MySQL FIND_IN_SET()。我们首先创建一个表 -
mysql> create table DemoTable1548 -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(20), -> ArrayListOfMarks varchar(100) -> ); Query OK, 0 rows affected (0.88 sec)
使用插入命令在表中插入一些记录 -
mysql> insert into DemoTable1548(StudentName,ArrayListOfMarks) values('Chris','56,78,90,87'); Query OK, 1 row affected (0.29 sec) mysql> insert into DemoTable1548(StudentName,ArrayListOfMarks) values('Bob','90,78,65'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable1548(StudentName,ArrayListOfMarks) values('David','91,34,56,78,87'); Query OK, 1 row affected (0.16 sec)
使用选择语句显示表中的所有记录 -
mysql> select * from DemoTable1548;
这将产生以下输出 -
+-----------+-------------+------------------+ | StudentId | StudentName | ArrayListOfMarks | +-----------+-------------+------------------+ | 1 | Chris | 56,78,90,87 | | 2 | Bob | 90,78,65 | | 3 | David | 91,34,56,78,87 | +-----------+-------------+------------------+ 3 rows in set (0.00 sec)
以下是从逗号分隔的值匹配中提取特定记录的查询 -
mysql> select * from DemoTable1548 where find_in_set('87',ArrayListOfMarks);
这将产生以下输出 -
+-----------+-------------+------------------+ | StudentId | StudentName | ArrayListOfMarks | +-----------+-------------+------------------+ | 1 | Chris | 56,78,90,87 | | 3 | David | 91,34,56,78,87 | +-----------+-------------+------------------+ 2 rows in set (0.00 sec)
广告