用 MySQL 中的分隔符字符串分隔字符串的左侧部分?
你可以使用 MySQL 中的 substring_index() 函数来分割字符串的左侧部分。语法如下 −
SELECT yourColumnName1,.....N,SUBSTRING_INDEX(yourColumnName,’yourSeperatorSymbol’,1) as anyVariableName from yourTableName;
值 1 表示你可以获得字符串的左侧部分。为了验证上述语法,让我们创建一个表。创建表的查询如下 −
mysql> create table LeftStringDemo -> ( -> Id int, -> Words varchar(100) -> ); Query OK, 0 rows affected (0.92 sec)
使用 insert 命令向表中插入一些记录。查询如下 −
mysql> insert into LeftStringDemo values(1,'MySQL==6789'); Query OK, 1 row affected (0.19 sec) mysql> insert into LeftStringDemo values(2,'Java==Object Oriented'); Query OK, 1 row affected (0.21 sec) mysql> insert into LeftStringDemo values(3,'C Language==Procedural Programming'); Query OK, 1 row affected (0.18 sec) mysql> insert into LeftStringDemo values(4,'PL/SQL==Structured Programming'); Query OK, 1 row affected (0.16 sec)
使用 select 语句显示表中的所有记录。查询如下 −
mysql> select *from LeftStringDemo;
输出如下
+------+------------------------------------+ | Id | Words | +------+------------------------------------+ | 1 | MySQL==6789 | | 2 | Java==Object Oriented | | 3 | C Language==Procedural Programming | | 4 | PL/SQL==Structured Programming | +------+------------------------------------+ 4 rows in set (0.00 sec)
以下查询基于分隔符字符串 ‘==’ 获取字符串列 ‘Words’ 的左侧部分
mysql> select Id, substring_index(Words, '==', 1) as OnlyLefthandsideValue from LeftStringDemo;
输出如下
+------+-----------------------+ | Id | OnlyLefthandsideValue | +------+-----------------------+ | 1 | MySQL | | 2 | Java | | 3 | C Language | | 4 | PL/SQL | +------+-----------------------+ 4 rows in set (0.00 sec)
广告