MySQL 查询是否只保留列值中的前 2 个字符并删除其余字符?

mysqlmysqli database

要只保留前两个字符并删除其余字符,请使用 SUBSTRING()。

首先我们创建一个表 −

mysql> create table DemoTable743 (SubjectName varchar(100));
Query OK, 0 rows affected (0.54 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable743 values('MySQL');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable743 values('Java');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable743 values('MongoDB');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable743 values('Python');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable743 values('Data Structure');
Query OK, 1 row affected (0.68 sec)
mysql> insert into DemoTable743 values('Algorithm');
Query OK, 1 row affected (0.12 sec)

使用 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);
Query OK, 6 rows affected (0.12 sec)
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)

相关文章