在 MySQL 查询中选择第一个单词?
mysqlmysqli database更新于 2025/5/27 19:56:17
要选择 MySQL 查询中的第一个单词,可以使用 SUBSTRING_INDEX()。
以下是语法−
select substring_index(yourColumnName,' ',1) as anyAliasName from yourTableName;
首先我们创建一个表 −
mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentFullName varchar(40) ); Query OK, 0 rows affected (0.61 sec)
使用 insert 命令在表中插入记录 −
mysql> insert into DemoTable(StudentFullName) values('John Smith');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable(StudentFullName) values('Carol Taylor');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentFullName) values('Bob Williams');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentFullName) values('David Miller');
Query OK, 1 row affected (0.16 sec)
使用 select 命令显示表中的记录 −
mysql> select *from DemoTable;
这将产生以下输出 −
+-----------+-----------------+ | StudentId | StudentFullName | +-----------+-----------------+ | 1 | John Smith | | 2 | Carol Taylor | | 3 | Bob Williams | | 4 | David Miller | +-----------+-----------------+ 4 rows in set (0.00 sec)
以下是在 MySQL 查询 − 中选择第一个单词的查询
mysql> select substring_index(StudentFullName,' ',1) as FirstWord from DemoTable;
这将产生以下输出,显示第一个单词 −
+-----------+ | FirstWord | +-----------+ | John | | Carol | | Bob | | David | +-----------+ 4 rows in set (0.00 sec)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

