如何從包含檔案路徑的列中獲取 MySQL 中的左子串?顯示不包括檔名在內的整個檔案路徑字串?


要獲取左子串,請將 LEFT() 與 substring_index() 配合使用。例如,假設檔案路徑為 −

“/MyFile/JavaProgram/Hello.java “

在此,我們將瞭解如何顯示整個檔案路徑,不包括檔名,即 −

/MyFile/JavaProgram/

我們首先建立一個表 −

mysql> create table DemoTable
(
   FileLocation text
);
Query OK, 0 rows affected (0.57 sec

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

mysql> insert into DemoTable values('/MyFile/JavaProgram/Hello.java');
Query OK, 1 row affected (0.27 sec)
mysql> insert into DemoTable values('/C/AllPrograms/animation.gif');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('/E/FavFile/ChatProgram.java');
Query OK, 1 row affected (0.18 sec)

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

mysql> select *from DemoTable;

將生成以下輸出 −

+--------------------------------+
| FileLocation                   |
+--------------------------------+
| /MyFile/JavaProgram/Hello.java |
| /C/AllPrograms/animation.gif   |
| /E/FavFile/ChatProgram.java    |
+--------------------------------+
3 rows in set (0.00 sec)

以下是獲取 MySQL 中左子串的查詢 −

mysql> select left(FileLocation,char_length(FileLocation)-char_length(substring_index(FileLocation,'/',-1))) from DemoTable;

將生成以下輸出 −

+------------------------------------------------------------------------------------------------+
| left(FileLocation,char_length(FileLocation)-char_length(substring_index(FileLocation,'/',-1))) |
+------------------------------------------------------------------------------------------------+
| /MyFile/JavaProgram/                                                                           |
| /C/AllPrograms/                                                                                |
| /E/FavFile/                                                                                    |
+------------------------------------------------------------------------------------------------+
3 rows in set (0.00 sec)

更新於: 30-9-2019

301 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.