语法如下,以计算字段所有行中的所有字符-select sum(char_length(yourColumnName)) AS anyAliasName from yourTableName;
为了理解上述语法,让我们创建一个表。
创建表的查询如下-mysql> create table CountAllCharactersDemo
-> (
-> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
-> UserName varchar(20),
-> UserSubject text
-> );
使用insert命令在表中插入一些记录。查询如下-mysql> insert into CountAllCharactersDemo(UserName,UserSubject)
values('Larry','Introduction To Java');
mysql> insert into CountAllCharactersDemo(UserName,UserSubject)
values('Mike','Introduction To Computer Networks');
mysql> insert into CountAllCharactersDemo(UserName,UserSubject)
values('Sam','Introduction To C');
mysql> insert into CountAllCharactersDemo(UserName,UserSubject)
values('Carol','Introduction To Python');
mysql> insert into CountAllCharactersDemo(UserName,UserSubject)
values('David','Introduction To Spring And Hibernate Framework');
使用select语句显示表中的所有记录。查询如下-mysql> select *from CountAllCharactersDemo;
这是输出-+--------+----------+------------------------------------------------+
| UserId | UserName | UserSubject |
+--------+----------+------------------------------------------------+
| 1 | Larry | Introduction To Java |
| 2 | Mike | Introduction To Computer Networks |
| 3 | Sam | Introduction To C |
| 4 | Carol | Introduction To Python |
| 5 | David | Introduction To Spring And Hibernate Framework |
+--------+----------+------------------------------------------------+
5 rows in set (0.00 sec)
这是对MySQL中字段的所有行中的所有字符进行计数的查询。
情况1-计算总长度。
查询如下-mysql> select sum(char_length(UserSubject)) AS AllCharactersLength from
CountAllCharactersDemo;
这是输出-+---------------------+
| AllCharactersLength |
+---------------------+
| 138 |
+---------------------+
1 row in set (0.00 sec)
情况2-查询以计算每行长度-mysql> select UserId,UserName,UserSubject,char_length(UserSubject) AS Length from
CountAllCharactersDemo;
以下是输出-+--------+----------+------------------------------------------------+--------+
| UserId | UserName | UserSubject | Length |
+--------+----------+------------------------------------------------+--------+
| 1 | Larry | Introduction To Java | 20 |
| 2 | Mike | Introduction To Computer Networks | 33 |
| 3 | Sam | Introduction To C | 17 |
| 4 | Carol | Introduction To Python | 22 |
| 5 | David | Introduction To Spring And Hibernate Framework | 46 |
+--------+----------+------------------------------------------------+--------+
5 rows in set (0.00 sec)