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

มีทางเลือกแทน CONCAT() ใน MySQL หรือไม่

มีครับ ทางเลือกคือ CONCAT_WS()

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

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

เพิ่มข้อมูลตัวอย่าง

mysql> insert into DemoTable(StudentName) values('Chris');
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable(StudentName) values('Robert');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(StudentName) values('Bob');
Query OK, 1 row affected (0.12 sec)

แสดงข้อมูลทั้งหมด

mysql> select * from DemoTable;

ผลลัพธ์

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 1         | Chris       |
| 2         | Robert      |
| 3         | Bob         |
+-----------+-------------+
3 rows in set (0.00 sec)

ตัวอย่างใช้ CONCAT_WS() แทน CONCAT()

mysql> select concat_ws(SPACE(2), 'Student Name is:', StudentName) from DemoTable;

ผลลัพธ์

+-----------------------------------------------------+
| concat_ws(SPACE(2), 'Student Name is:', StudentName) |
+-----------------------------------------------------+
| Student Name is:  Chris                             |
| Student Name is:  Robert                            |
| Student Name is:  Bob                               |
+-----------------------------------------------------+
3 rows in set (0.04 sec)

คำอธิบาย: CONCAT_WS(separator, str1, str2, ...) - WS = With Separator รวมสตริงด้วยตัวคั่นระหว่างอาร์กิวเมนต์ ต่างจาก CONCAT() ที่ต่อติดกันโดยไม่มีตัวคั่น