Giới thiệu
Dùng hàm CONCAT() để nối chuỗi giá trị số với ký tự '%' khi hiển thị, không thay đổi dữ liệu gốc.
Ví dụ minh họa
Tạo bảng và chèn dữ liệu
mysql> CREATE TABLE DemoTable (
StudentId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
StudentName VARCHAR(100),
StudentScore INT
);
mysql> INSERT INTO DemoTable (StudentName, StudentScore) VALUES
('John', 65), ('Chris', 98), ('Robert', 91);
Truy vấn thêm %
mysql> SELECT StudentId, StudentName, CONCAT(StudentScore, '%') AS StudentScore FROM DemoTable;
Kết quả
+-----------+-------------+--------------+ | StudentId | StudentName | StudentScore | +-----------+-------------+--------------+ | 1 | John | 65% | | 2 | Chris | 98% | | 3 | Robert | 91% | +-----------+--------------+
Mở rộng
Format số thập phân + %
SELECT CONCAT(ROUND(score * 100, 2), '%') FROM grades;
Thêm tiền tố/hậu tố khác
CONCAT('$', price) -- $100
CONCAT(quantity, ' pcs') -- 5 pcs
CONCAT('ID: ', id) -- ID: 123
Cập nhật dữ liệu thật (nếu cần)
UPDATE DemoTable SET StudentScore = CONCAT(StudentScore, '%');
Lưu ý: Cột phải kiểu VARCHAR/TEXT để lưu chuỗi có %. Không khuyến khích lưu format hiển thị vào DB.