如何在 MySQL 中的一张文件名表中选择所有不同的文件名扩展名?
你可以结合使用 DISTINCT 和 SUBSTRING_INDEX() 来提取文件名扩展名。我们首先创建一个表−
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, FileName text ); Query OK, 0 rows affected (0.75 sec)
使用 Insert 命令将记录插入表中 −
mysql> insert into DemoTable(FileName) values('AddTwoValue.java'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(FileName) values('Image1.png'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(FileName) values('MultiplicationOfTwoNumbers.java'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(FileName) values('Palindrome.c'); Query OK, 1 row affected (0.16 sec) mysql> insert into DemoTable(FileName) values('FoodCart.png'); Query OK, 1 row affected (0.25 sec) mysql> insert into DemoTable(FileName) values('Permutation.py'); Query OK, 1 row affected (0.18 sec)
使用 select 语句在表中显示所有记录 −
mysql> select * from DemoTable;
这将产生以下输出 −
+----+---------------------------------+ | Id | FileName | +----+---------------------------------+ | 1 | AddTwoValue.java | | 2 | Image1.png | | 3 | MultiplicationOfTwoNumbers.java | | 4 | Palindrome.c | | 5 | FoodCart.png | | 6 | Permutation.py | +----+---------------------------------+ 6 rows in set (0.00 sec)
以下是从一张文件名表中选择所有不同的文件名扩展名的查询 −
mysql> SELECT DISTINCT SUBSTRING_INDEX(FileName,'.',-1) FROM DemoTable;
这将产生以下输出 −
+----------------------------------+ | SUBSTRING_INDEX(FileName,'.',-1) | +----------------------------------+ | java | | png | | c | | py | +----------------------------------+ 4 rows in set (0.03 sec)
广告