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

ต่อข้อความใน SELECT clause ของ MySQL ด้วย CONCAT


คำสั่งหลัก

ใช้ CONCAT() รวมคอลัมน์/ข้อความคงที่ใน SELECT clause

รูปแบบคำสั่ง

SELECT CONCAT(col1, ' text ', col2, ' more text') AS alias FROM table;

ตัวอย่างครบถ้วน

1. สร้างตาราง

mysql> create table ConcatenatingDemo 
    -> ( 
    -> UserId int NOT NULL AUTO_INCREMENT PRIMARY KEY, 
    -> UserName varchar(20), 
    -> UserCountryName varchar(20) 
    -> ); 
Query OK, 0 rows affected (0.82 sec)

2. เพิ่มข้อมูล

mysql> insert into ConcatenatingDemo(UserName,UserCountryName) values('John','US'); 
Query OK, 1 row affected (0.14 sec)
mysql> insert into ConcatenatingDemo(UserName,UserCountryName) values('Carol','UK'); 
Query OK, 1 row affected (0.13 sec)
mysql> insert into ConcatenatingDemo(UserName,UserCountryName) values('Bob','AUS'); 
Query OK, 1 row affected (0.15 sec)
mysql> insert into ConcatenatingDemo(UserName,UserCountryName) values('David','US'); 
Query OK, 1 row affected (0.29 sec)

3. ดูข้อมูล

mysql> select * from ConcatenatingDemo;
+--------+----------+-----------------+
| UserId | UserName | UserCountryName |
+--------+----------+-----------------+
| 1      | John     | US              |
| 2      | Carol    | UK              |
| 3      | Bob      | AUS             |
| 4      | David    | US              |
+--------+----------+-----------------+

4. CONCAT สร้างประโยค

mysql> select concat(UserName, ' belongs to ( ', UserCountryName, ' )') as AddingTextDemo from ConcatenatingDemo;
+-------------------------+
| AddingTextDemo          |
+-------------------------+
| John belongs to ( US )  |
| Carol belongs to ( UK ) |
| Bob belongs to ( AUS )  |
| David belongs to ( US ) |
+-------------------------+

CONCAT_WS: With Separator (จัดการ NULL อัตโนมัติ)

SELECT CONCAT_WS(' - ', first_name, last_name, email) FROM users;

ถ้าคอลัมน์ไหน NULL จะข้ามไป ไม่มี separator เหลือ

CONCAT กับ NULL

SELECT CONCAT('Hello', NULL, 'World');  -- → NULL ❌
SELECT CONCAT('Hello', COALESCE(middle, ''), 'World');  -- ใช้ COALESCE กัน NULL
SELECT CONCAT_WS(' ', 'Hello', middle, 'World');  -- ใช้ CONCAT_WS ดีกว่า

MySQL 8.0: ใช้ || (Oracle style) ต้อง SET sql_mode

SET sql_mode = 'PIPES_AS_CONCAT';
SELECT 'Hello' || ' ' || 'World';  -- 'Hello World'

ประยุกต์ใช้: สร้าง Dynamic SQL / Labels

SELECT CONCAT('UPDATE users SET status=', QUOTE(new_status), ' WHERE id=', id) 
FROM pending_changes;

สรุป: CONCAT() ฟังก์ชันพื้นฐานสำหรับ string concatenation ใน MySQL ใช้ใน SELECT, UPDATE, WHERE ได้ทั้งหมด