在特定字串連字元之前獲取所有字串的 MySQL 查詢
為此,可以使用 SUBSTRING_INDEX()。讓我們先建立一個表 −
mysql> create table DemoTable1857 ( Name varchar(20) ); Query OK, 0 rows affected (0.00 sec)
透過使用插入命令在表中插入一些記錄 −
mysql> insert into DemoTable1857 values('John-Smith'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1857 values('Brown-Chris'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1857 values('David-Carol-Miller'); Query OK, 1 row affected (0.00 sec)
透過使用選擇語句顯示錶中的所有記錄 −
mysql> select * from DemoTable1857;
這將生成以下輸出 −
+--------------------+ | Name | +--------------------+ | John-Smith | | Brown-Chris | | David-Carol-Miller | +--------------------+ 3 rows in set (0.00 sec)
以下是獲取特定字元連字元之前所有字元的查詢 −
mysql> select substring_index(Name,'-',1) Name from DemoTable1857;
這將生成以下輸出 −
+-------+ | Name | +-------+ | John | | Brown | | David | +-------+ 3 rows in set (0.00 sec)
廣告