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)

更新日期:12-Dec-2019

787 檢視次數

開啟您的 職業生涯

完成課程即可獲得認證

立即開始
廣告