Concatenate สตริงจากหลายคอลัมน์ด้วย CONCAT()
ฟังก์ชัน CONCAT(str1, str2, ...) รวมสตริงหลายตัวเข้าด้วยกัน คืนค่า NULL หากมีอาร์กิวเมนต์ใดเป็น NULL
รูปแบบคำสั่ง (Syntax)
SELECT CONCAT(column1, ' ', column2) AS combined_name
FROM yourTableName;
ตัวอย่างการใช้งาน
สร้างตาราง concatenateTwoColumnsDemo:
CREATE TABLE concatenateTwoColumnsDemo (
StudentId INT,
StudentName VARCHAR(200),
StudentAge INT
);
ข้อมูล:
| StudentId | StudentName | StudentAge |
|---|---|---|
| 1 | Sam | 21 |
| 2 | David | 24 |
| 3 | Carol | 22 |
| 4 | Johnson | 19 |
รวม Name และ Age (คั่นด้วย Space):
SELECT CONCAT(StudentName, ' ', StudentAge) AS NameAndAgeColumn
FROM concatenateTwoColumnsDemo;
ผลลัพธ์:
| NameAndAgeColumn |
|---|
| Sam 21 |
| David 24 |
| Carol 22 |
| Johnson 19 |
ฟังก์ชันเกี่ยวข้อง
- CONCAT_WS(separator, str1, str2, ...) - รวมด้วย Separator ข้าม NULL ไป (แนะนำใช้แทน CONCAT)
- GROUP_CONCAT() - รวมค่าจากหลายแถวเป็นสตริงเดียว
ตัวอย่าง CONCAT_WS (จัดการ NULL ได้ดีกว่า)
SELECT CONCAT_WS(' ', StudentName, StudentAge, 'years old')
FROM concatenateTwoColumnsDemo;
ผล: Sam 21 years old (แม้ StudentAge จะเป็น NULL ก็ไม่มี Space ค้าง)