從 MySQL 中一列包含字串形式的檔名的資料中獲取該檔案的副檔名?


為此,請使用 substring_index() 函式。

語法如下

select substring_index(yourColumnName, '. ', -1) AS anyAliasNamefrom yourTableName;

我們先建立一個表。建立表的查詢如下

mysql> create table AllFiles
   - > (
   - > Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   - > UserName varchar(10),
   - > FileName varchar(100)
   - > );
Query OK, 0 rows affected (0.65 sec)

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

查詢如下

mysql> insert into AllFiles(UserName,FileName) values('Larry','AddTwoNumber.java');
Query OK, 1 row affected (0.18 sec)
mysql> insert into AllFiles(UserName,FileName) values('Mike','AddTwoNumber.python');
Query OK, 1 row affected (0.15 sec)
mysql> insert into AllFiles(UserName,FileName) values('Sam','MatrixMultiplication.c');
Query OK, 1 row affected (0.16 sec)
mysql> insert into AllFiles(UserName,FileName) values('Carol','vector.cpp');
Query OK, 1 row affected (0.15 sec)

使用 select 語句從表中顯示所有記錄。

查詢如下

mysql> select *from AllFiles;

以下是輸出

+----+----------+------------------------+
| Id | UserName | FileName               |
+----+----------+------------------------+
|  1 | Larry    | AddTwoNumber.java      |
|  2 | Mike     | AddTwoNumber.python    |
|  3 | Sam      | MatrixMultiplication.c |
|  4 | Carol    | vector.cpp             |
+----+----------+------------------------+
4 rows in set (0.00 sec)

以下是在 MySQL 中僅獲取副檔名的查詢

mysql> select substring_index(FileName,'.',-1) AS ALLFILENAMEEXTENSIONS from AllFiles;

以下是輸出

+-----------------------+
| ALLFILENAMEEXTENSIONS |
+-----------------------+
| java                  |
| python                |
| c                     |
| cpp                   |
+-----------------------+
4 rows in set (0.00 sec)

更新於:30-Jul-2019

919 次瀏覽

開啟你的 職業 生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.