在 MySQL 中用分隔符字符串分割字符串的左侧部分?
mysqlmysqli database
您可以使用 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)