如何從 MySQL 中帶有分號的值列表中查詢特定記錄?


為此,你可以使用 FIND_IN_SET()。讓我們首先建立一個表 -

mysql> create table DemoTable
(
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Value varchar(100)
);
Query OK, 0 rows affected (2.49 sec)

使用 insert 命令在表中插入一些記錄 -

mysql> insert into DemoTable(Value) values('100;200;300');
Query OK, 1 row affected (0.42 sec)
mysql> insert into DemoTable(Value) values('1;300;400');
Query OK, 1 row affected (0.58 sec)
mysql> insert into DemoTable(Value) values('6;7;8;9;10');
Query OK, 1 row affected (0.29 sec)
mysql> insert into DemoTable(Value) values('1;2;3;4;5');
Query OK, 1 row affected (9.36 sec)
mysql> insert into DemoTable(Value) values('3;8;9;10');
Query OK, 1 row affected (0.46 sec)

使用 select 語句在表中顯示所有記錄 -

mysql> select *from DemoTable;

這將會產生以下輸出 -

+----+-------------+
| Id | Value       |  
+----+-------------+
|  1 | 100;200;300 |
|  2 | 1;300;400   |
|  3 | 6;7;8;9;10  |
|  4 | 1;2;3;4;5   |
|  5 | 3;8;9;10    |   
+----+-------------+
5 rows in set (0.00 sec)

以下是使用分號從值列表中查詢特定記錄的查詢 -

mysql> select *from DemoTable where find_in_set(8, replace(Value, ';', ',')) > 0;

這將會產生以下輸出 -

+----+------------+
| Id | Value      |
+----+------------+
|  3 | 6;7;8;9;10 |
|  5 | 3;8;9;10   |
+----+------------+
2 rows in set (0.00 sec)

更新於: 26-Sep-2019

108 次瀏覽

啟動你的 職業

透過完成課程進行認證

開始
廣告
© . All rights reserved.