更新 MySQL 中的表并在新列中仅显示首字母名称
mysqlmysqli database
要获取首字母,请使用 left() 概念以及 substring_index()。
让我们创建一个表 −
mysql> create table demo13 −> ( −> full_name varchar(100), −> short_name varchar(20) −> ); Query OK, 0 rows affected (1.18 sec)
使用 insert 命令向表中插入一些记录 −
mysql> insert into demo13(full_name) values('John Smith');
Query OK, 1 row affected (0.27 sec)
mysql> insert into demo13(full_name) values('David Miller');
Query OK, 1 row affected (0.13 sec)
mysql> insert into demo13(full_name) values('Chris Brown');
Query OK, 1 row affected (0.28 sec)
使用 select 语句显示表中的记录 −
mysql> select *from demo13;
这将产生以下输出 −
+--------------+------------+ | full_name | short_name | +--------------+------------+ | John Smith | NULL | | David Miller | NULL | | Chris Brown | NULL | +--------------+------------+ 3 rows in set (0.00 sec)
以下是更新表并获取首字母名称的查询 −
mysql> update demo13 −> set short_name= concat( −> left(full_name, 1), −> left(substring_index(full_name, ' ', −1), 1) −> ); Query OK, 3 rows affected (0.14 sec) Rows matched: 3 Changed: 3 Warnings: 0
使用 select 语句显示表中的记录 −
mysql> select *from demo13;
这将产生以下输出 −
+--------------+------------+ | full_name | short_name | +--------------+------------+ | John Smith | JS | | David Miller | DM | | Chris Brown | CB | +--------------+------------+ 3 rows in set (0.00 sec)
相关文章
有用资源
mysql 参考教程 - 该教程包含有关 mysql 的更多信息:https://www.cainiaomax.com/mysql/

