使用 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)

看看上面的示例輸出,空格也計算在內。

更新日期:2019 年 7 月 30 日

19 萬+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.