Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> MySQL

Đếm tổng số ký tự của một cột trên tất cả hàng trong MySQL

Sử dụng hàm CHAR_LENGTH() kết hợp với SUM() để tính tổng độ dài chuỗi của một cột trên toàn bộ bảng.

Cú pháp

SELECT SUM(CHAR_LENGTH(tên_cột)) AS tên_alias FROM tên_bảng;

Ví dụ minh họa

Tạo bảng demo:

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)

Chèn dữ liệu:

mysql> INSERT INTO CountAllCharactersDemo(UserName, UserSubject) VALUES
    -> ('Larry', 'Introduction To Java'),
    -> ('Mike', 'Introduction To Computer Networks'),
    -> ('Sam', 'Introduction To C'),
    -> ('Carol', 'Introduction To Python'),
    -> ('David', 'Introduction To Spring And Hibernate Framework');

Xem dữ liệu:

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 |
+--------+----------+------------------------------------------------+

Trường hợp 1: Tính tổng độ dài tất cả hàng

mysql> SELECT SUM(CHAR_LENGTH(UserSubject)) AS AllCharactersLength 
    -> FROM CountAllCharactersDemo;
+---------------------+
| AllCharactersLength |
+---------------------+
| 138                 |
+---------------------+

Trường hợp 2: Tính độ dài từng hàng

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     |
+--------+----------+------------------------------------------------+--------+

Lưu ý: CHAR_LENGTH() đếm số ký tự (character), trong khi LENGTH() đếm số byte. Với UTF-8, một ký tự có thể chiếm 1-4 byte.