MySQL查询保留列值中仅前2个字符并删除其余字符?
要仅保留前两个字符并删除其余字符,请使用SUBSTRING()
。
让我们首先创建一个表-
mysql> create table DemoTable743 (SubjectName varchar(100));
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable743 values('MySQL'); mysql> insert into DemoTable743 values('Java'); mysql> insert into DemoTable743 values('MongoDB'); mysql> insert into DemoTable743 values('Python'); mysql> insert into DemoTable743 values('Data Structure'); mysql> insert into DemoTable743 values('Algorithm');
使用select语句显示表中的所有记录-
mysql> select *from DemoTable743;
这将产生以下输出-
+----------------+ | SubjectName | +----------------+ | MySQL | | Java | | MongoDB | | Python | | Data Structure | | Algorithm | +----------------+ 6 rows in set (0.00 sec)
以下是查询以将前2个字符保留在列值中并删除其余字符-
mysql> update DemoTable743 set SubjectName=SUBSTRING(SubjectName,1,2); Rows matched: 6 Changed: 6 Warnings: 0
让我们再次检查表记录-
mysql> select *from DemoTable743;
这将产生以下输出-
+-------------+ | SubjectName | +-------------+ | My | | Ja | | Mo | | Py | | Da | | Al | +-------------+ 6 rows in set (0.00 sec)