如何为 MySQL 中的字段应用 Substring() 以获取部分字符串?
可以在 MySQL 中为字段使用 substring() 以获取部分字符串。以下是语法 -
select substring(yourColumnName,yourStartingIndex,yourEndingIndex) from yourTableName;
让我们首先创建一个表 -
mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, Title longtext ); Query OK, 0 rows affected (0.57 sec)
使用插入命令向表中插入记录 -
mysql> insert into DemoTable(Title) values('MySQL is a relational database management system'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(Title) values('MongoDB is a popular No SQL database'); Query OK, 1 row affected (0.18 sec)
使用 select 语句显示表中的所有记录 -
mysql> select * from DemoTable;
这将产生以下输出 -
+----+--------------------------------------------------+ | Id | Title | +----+--------------------------------------------------+ | 1 | MySQL is a relational database management system | | 2 | MongoDB is a popular No SQL database | +----+--------------------------------------------------+ 2 rows in set (0.00 sec)
以下是使用 substring() 方法的查询 -
mysql> select substring(Title,1,21) from DemoTable;
这将产生以下输出 -
+-----------------------+ | substring(Title,1,21) | +-----------------------+ | MySQL is a relational | | MongoDB is a popular | +-----------------------+ 2 rows in set (0.00 sec)
广告