如何為 MySQL 中的欄位應用 Substring() 以獲取部分字串?


可以在 MySQL 中為欄位使用 substring() 以獲取部分字串。以下是語法 -

select substring(yourColumnName,yourStartingIndex,yourEndingIndex) from yourTableName;

讓我們首先建立一個表 -

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Title longtext
   );
Query OK, 0 rows affected (0.57 sec)

使用插入命令向表中插入記錄 -

mysql> insert into DemoTable(Title) values('MySQL is a relational database management system');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable(Title) values('MongoDB is a popular No SQL database');
Query OK, 1 row affected (0.18 sec)

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

mysql> select * from DemoTable;

這將產生以下輸出 -

+----+--------------------------------------------------+
| Id | Title                                            |
+----+--------------------------------------------------+
| 1  | MySQL is a relational database management system |
| 2  | MongoDB is a popular No SQL database             |
+----+--------------------------------------------------+
2 rows in set (0.00 sec)

以下是使用 substring() 方法的查詢 -

mysql> select substring(Title,1,21) from DemoTable;

這將產生以下輸出 -

+-----------------------+
| substring(Title,1,21) |
+-----------------------+
| MySQL is a relational |
| MongoDB is a popular  |
+-----------------------+
2 rows in set (0.00 sec)

更新於: 30-7 月-2019

185 次瀏覽

開啟你的 職業生涯

完成課程以獲得認證

開始
廣告