使用 MySQL 查詢獲取字串的最後 5 個字元?
若要獲取帶有 MySQL 的字串的前 n 個字元,請使用 LEFT()。若要獲取字串的最後 n 個字元,MySQL 中使用了 RIGHT() 方法。
RIGHT() 方法的語法如下 −
SELECT RIGHT(yourColumnName, valueOfN) as anyVariableName from yourTableName;
為理解上述概念,讓我們建立一個表。建立表的查詢如下 −
mysql> create table gettingLast5Characters −> ( −> BookName varchar(100) −> ); Query OK, 0 rows affected (0.73 sec)
現在,你可以使用 insert 命令在表中插入記錄。查詢如下 −
mysql> insert into gettingLast5Characters values('Introduction to C');
Query OK, 1 row affected (0.19 sec)
mysql> insert into gettingLast5Characters values('C in Depth');
Query OK, 1 row affected (0.18 sec)
mysql> insert into gettingLast5Characters values('Introduction to Java');
Query OK, 1 row affected (0.18 sec)
mysql> insert into gettingLast5Characters values('Let us C');
Query OK, 1 row affected (0.51 sec)使用 select 語句顯示錶中的所有記錄。顯示所有記錄的查詢如下 −
mysql> select *from gettingLast5Characters;
以下是輸出 −
+----------------------+ | BookName | +----------------------+ | Introduction to C | | C in Depth | | Introduction to Java | | Let us C | +----------------------+ 4 rows in set (0.00 sec)
以下是獲取字串最後 5 個字元的查詢 −
mysql> select RIGHT(BookName,5) as Last5Character from gettingLast5Characters;
以下是輸出 −
+----------------+ | Last5Character | +----------------+ | to C | | Depth | | Java | | us C | +----------------+ 4 rows in set (0.04 sec)
看看上面的示例輸出,空格也計算在內。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP