要选择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) );
使用插入命令在表中插入记录-
mysql> insert into DemoTable(StudentFullName) values('John Smith'); mysql> insert into DemoTable(StudentFullName) values('Carol Taylor'); mysql> insert into DemoTable(StudentFullName) values('Bob Williams'); mysql> insert into DemoTable(StudentFullName) values('David Miller');
使用选择命令显示表中的记录-
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)