MySQL 查询从数组中获取匹配的特定记录(逗号分隔值)
mysqlmysqli database更新于 2024/2/6 11:38:00
要从逗号分隔值中获取记录,请使用 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)
使用 insert 命令在表中插入一些记录 −
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)
使用 select 语句显示表中的所有记录 −
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)