如何在 MySQL 中查詢具有給定字首的字串?


可以使用 LIKE 運算子查詢具有給定字首的字串。

語法如下

select *from yourTableName where yourColumnName LIKE 'yourPrefixValue%';

為了理解上述語法,讓我們建立一個表。建立表的查詢如下

mysql> create table findStringWithGivenPrefixDemo
   -> (
   -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> UserMessage text
   -> );
Query OK, 0 rows affected (0.82 sec)

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

查詢如下

mysql> insert into findStringWithGivenPrefixDemo(UserMessage) values('Hi Good Morning !!!');
Query OK, 1 row affected (0.17 sec)
mysql> insert into findStringWithGivenPrefixDemo(UserMessage) values('Hey I am busy!!');
Query OK, 1 row affected (0.20 sec)
mysql> insert into findStringWithGivenPrefixDemo(UserMessage) values('Hello what are you doing!!!');
Query OK, 1 row affected (0.47 sec)
mysql> insert into findStringWithGivenPrefixDemo(UserMessage) values('Hi I am learning MongoDB!!!');
Query OK, 1 row affected (0.15 sec)

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

查詢如下

mysql> select *from findStringWithGivenPrefixDemo;

輸出如下

+--------+-----------------------------+
| UserId | UserMessage                 |
+--------+-----------------------------+
| 1      | Hi Good Morning !!!         |
| 2      | Hey I am busy!!             |
| 3      | Hello what are you doing!!! |
| 4      | Hi I am learning MongoDB!!! |
+--------+-----------------------------+
4 rows in set (0.00 sec)

以下是如何查詢具有給定字首的字串

mysql> select *from findStringWithGivenPrefixDemo where UserMessage LIKE 'Hi%';

以下是僅顯示字首為“嗨”的字串的輸出

+--------+-----------------------------+
| UserId | UserMessage                 |
+--------+-----------------------------+
| 1      | Hi Good Morning !!!         |
| 4      | Hi i am learning MongoDB!!! |
+--------+-----------------------------+
2 rows in set (0.00 sec)

更新於: 2019 年 7 月 30 日

3K+ 瀏覽

職業生涯起步

完成課程,獲得認證

開始
廣告