在 MySQL 查詢中選擇第一個單詞?
要選擇 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)
廣告