當分組記錄具有多個相匹配的字串時,MySQL Select 怎麼辦?


對此可以使用正則表示式。我們首先建立一個表 -

mysql> create table DemoTable
   (
   ProductId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   ProductName varchar(20)
   );
Query OK, 0 rows affected (0.19 sec)

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

mysql> insert into DemoTable(ProductName) values('Product-1');
Query OK, 1 row affected (0.05 sec)

mysql> insert into DemoTable(ProductName) values('Product2');
Query OK, 1 row affected (0.06 sec)

mysql> insert into DemoTable(ProductName) values('Product1');
Query OK, 1 row affected (0.04 sec)

mysql> insert into DemoTable(ProductName) values('Product-3');
Query OK, 1 row affected (0.05 sec)

mysql> insert into DemoTable(ProductName) values('Product3');
Query OK, 1 row affected (0.05 sec)

mysql> insert into DemoTable(ProductName) values('Product-4');
Query OK, 1 row affected (0.09 sec)

mysql> insert into DemoTable(ProductName) values('Product4');
Query OK, 1 row affected (0.05 sec)

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

mysql> select *from DemoTable;

這將產生以下輸出 -

+-----------+-------------+
| ProductId | ProductName |
+-----------+-------------+
| 1         | Product-1   |
| 2         | Product2    |
| 3         | Product1    |
| 4         | Product-3   |
| 5         | Product3    |
| 6         | Product-4   |
| 7         | Product4    |
+-----------+-------------+
7 rows in set (0.00 sec)

以下是具有多個匹配字串的分組記錄的查詢 -

mysql> select *from DemoTable
where ProductName regexp 'Product[1234].*';

這將產生以下輸出 -

+-----------+-------------+
| ProductId | ProductName |
+-----------+-------------+
| 2         | Product2    |
| 3         | Product1    |
| 5         | Product3    |
| 7         | Product4    |
+-----------+-------------+
4 rows in set (0.00 sec)

更新於:2019 年 7 月 30 日

59 次瀏覽

開啟您的 職業生涯

透過完成課程,獲得認證

開始
廣告
© . All rights reserved.