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

MySQL: รวม 2 คอลัมน์เป็น 1 คั่นด้วย Hyphen (CONCAT)

การต่อสตริง 2 คอลัมน์ด้วย CONCAT

ใช้ CONCAT(col1, '-', col2) รวมค่าจาก 2 คอลัมน์ คั่นด้วย Hyphen

ตัวอย่าง

mysql> create table DemoTable835(
    CountryCode int,
    CountryName varchar(100) );
Query OK, 0 rows affected (0.63 sec)
mysql> insert into DemoTable835 values(100, 'US');
mysql> insert into DemoTable835 values(101, 'UK');
mysql> insert into DemoTable835 values(102, 'AUS');
mysql> insert into DemoTable835 values(103, 'ENG');

คำสั่ง CONCAT

mysql> select concat(CountryCode, '-', CountryName) from DemoTable835;

ผลลัพธ์:

+-------------------------------------+
| concat(CountryCode, '-', CountryName) |
+-------------------------------------+
| 100-US                              |
| 101-UK                              |
| 102-AUS                             |
| 103-ENG                             |
+-------------------------------------+

การใช้งานเพิ่มเติม

-- ตั้งชื่อ Alias
SELECT CONCAT(CountryCode, '-', CountryName) AS country_code_name FROM DemoTable835;

-- ใช้ CONCAT_WS (With Separator) - ข้าม NULL
SELECT CONCAT_WS('-', CountryCode, CountryName) FROM DemoTable835;

-- สร้าง View
CREATE VIEW v_country_codes AS 
SELECT CountryCode, CountryName, CONCAT(CountryCode, '-', CountryName) AS code_name
FROM DemoTable835;

CONCAT vs CONCAT_WS

ฟังก์ชันพฤติกรรมเมื่อมี NULLตัวคั่น
CONCAT(a, '-', b)คืน NULL ทั้งหมดระบุเอง
CONCAT_WS('-', a, b)ข้าม NULL, ต่อเฉพาะที่มีค่าอาร์กิวเมนต์แรก

สรุป

ใช้ CONCAT(col1, '-', col2) รวม 2 คอลัมน์คั่น Hyphen ใช้ CONCAT_WS ถ้าอาจมี NULL และต้องการข้าม