在 MySQL 中有沒有辦法選擇部分匹配的值?


要部分匹配,請使用 LIKE 運算子。我們先建立一個表 -

mysql> create table DemoTable806(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentName varchar(100),
   StudentSubject varchar(100)
);
Query OK, 0 rows affected (0.57 sec)

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

mysql> insert into DemoTable806(StudentName,StudentSubject) values('Chris','Java in Depth With Data Structure');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable806(StudentName,StudentSubject) values('Robert','Introduction to MySQL');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable806(StudentName,StudentSubject) values('Bob','C++ in Depth With Data Structure And Algorithm');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable806(StudentName,StudentSubject) values('Adam','Introduction to MongoDB');
Query OK, 1 row affected (0.11 sec)

使用 select 語句顯示錶中的所有記錄 -

mysql> select *from DemoTable806;

這將產生以下輸出 -

+-----------+-------------+------------------------------------------------+
| StudentId | StudentName | StudentSubject                                 |
+-----------+-------------+------------------------------------------------+
|         1 | Chris       | Java in Depth With Data Structure              |
|         2 | Robert      | Introduction to MySQL                          |
|         3 | Bob         | C++ in Depth With Data Structure And Algorithm |
|         4 | Adam        | Introduction to MongoDB                        |
+-----------+-------------+------------------------------------------------+
4 rows in set (0.00 sec)

以下是選擇部分匹配的值的查詢 -

mysql> select *from DemoTable806 where StudentSubject LIKE '%Depth%';

這將產生以下輸出 -

+-----------+-------------+------------------------------------------------+
| StudentId | StudentName | StudentSubject                                 | 
+-----------+-------------+------------------------------------------------+
|         1 | Chris       | Java in Depth With Data Structure              |
|         3 | Bob         | C++ in Depth With Data Structure And Algorithm |
+-----------+-------------+------------------------------------------------+
2 rows in set (0.00 sec)

更新於: 2019-09-03

144 次瀏覽

開啟你的 事業

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.