Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MySQL

เพิ่มเครื่องหมาย % (เปอร์เซ็นต์) ท้ายค่าใน MySQL SELECT ด้วย CONCAT

ฟังก์ชัน CONCAT() ใน MySQL ใช้ต่อสตริงเข้าด้วยกัน สามารถนำมาเพิ่มเครื่องหมายเปอร์เซ็นต์ (% ) หรือข้อความอื่นๆ ท้ายค่าตัวเลขในคำสั่ง SELECT ได้

ตัวอย่างการสร้างตาราง

mysql> create table DemoTable ( 
    StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
    StudentName varchar(100), 
    StudentScore int ); 
Query OK, 0 rows affected (0.68 sec)

เพิ่มข้อมูลนักเรียนและคะแนน

mysql> insert into DemoTable(StudentName,StudentScore) values('John',65); 
Query OK, 1 row affected (0.09 sec)
mysql> insert into DemoTable(StudentName,StudentScore) values('Chris',98); 
Query OK, 1 row affected (0.30 sec)
mysql> insert into DemoTable(StudentName,StudentScore) values('Robert',91); 
Query OK, 1 row affected (0.09 sec)

แสดงข้อมูลก่อนเพิ่ม %

mysql> select * from DemoTable;
+-----------+-------------+--------------+
| StudentId | StudentName | StudentScore |
+-----------+-------------+--------------+
| 1         | John        | 65           |
| 2         | Chris       | 98           |
| 3         | Robert      | 91           |
+-----------+-------------+--------------+
3 rows in set (0.00 sec)

คำสั่ง SELECT เพิ่ม % ท้ายคะแนนด้วย CONCAT

mysql> select StudentId, StudentName, concat(StudentScore, '%') AS StudentScore 
from DemoTable;

ผลลัพธ์

+-----------+-------------+--------------+
| StudentId | StudentName | StudentScore |
+-----------+-------------+--------------+
| 1         | John        | 65%          |
| 2         | Chris       | 98%          |
| 3         | Robert      | 91%          |
+-----------+-------------+--------------+
3 rows in set (0.00 sec)

คำอธิบาย: CONCAT(StudentScore, '%') จะแปลงตัวเลขเป็นสตริงแล้วต่อ '%' ไปท้าย สามารถประยุกต์ใช้เพิ่มหน่วยอื่นๆ ได้ เช่น CONCAT(Price, ' บาท'), CONCAT(Name, ' (VIP)') ฯลฯ