如何在 MySQL 中计算某个字段的所有行中的所有字符?
mysqlmysqli database
计算某个字段的所有行中的所有字符的语法如下 −
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 -> ); Query OK, 0 rows affected (0.47 sec)
使用 insert 命令在表中插入一些记录。 查询语句如下 −
mysql> insert into CountAllCharactersDemo(UserName,UserSubject) values('Larry','Introduction To Java'); Query OK, 1 row affected (0.19 sec) mysql> insert into CountAllCharactersDemo(UserName,UserSubject) values('Mike','Introduction To Computer Networks'); Query OK, 1 row affected (0.21 sec) mysql> insert into CountAllCharactersDemo(UserName,UserSubject) values('Sam','Introduction To C'); Query OK, 1 row affected (0.18 sec) mysql> insert into CountAllCharactersDemo(UserName,UserSubject) values('Carol','Introduction To Python'); Query OK, 1 row affected (0.25 sec) mysql> insert into CountAllCharactersDemo(UserName,UserSubject) values('David','Introduction To Spring And Hibernate Framework'); Query OK, 1 row affected (0.15 sec)
使用 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)