การดึงคำแรก (First Word) จากสตริงใน MySQL
ใช้ SUBSTRING_INDEX(str, ' ', 1) เพื่อดึงส่วนก่อน Space แรก
SELECT SUBSTRING_INDEX(yourColumn, ' ', 1) AS first_word FROM yourTable;
ตัวอย่างการใช้งาน
สร้างตารางชื่อเต็ม:
mysql> create table DemoTable (
StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
StudentFullName varchar(40)
);
mysql> insert into DemoTable(StudentFullName) values('John Smith');
mysql> insert into DemoTable(StudentFullName) values('Carol Taylor');
mysql> insert into DemoTable(StudentFullName) values('Bob Williams');
mysql> insert into DemoTable(StudentFullName) values('David Miller');
ข้อมูล:
+-----------+-----------------+ | StudentId | StudentFullName | +-----------+-----------------+ | 1 | John Smith | | 2 | Carol Taylor | | 3 | Bob Williams | | 4 | David Miller | +-----------+-----------------+
คิวรีดึงคำแรก:
mysql> select substring_index(StudentFullName, ' ', 1) as FirstWord from DemoTable;
+-----------+ | FirstWord | +-----------+ | John | | Carol | | Bob | | David | +-----------+
การประยุกต์:
- คำสุดท้าย:
SUBSTRING_INDEX(StudentFullName, ' ', -1)→ Smith, Taylor, Williams, Miller - คำที่ 2:
SUBSTRING_INDEX(SUBSTRING_INDEX(StudentFullName, ' ', 2), ' ', -1) - หากไม่มี Space: คืนค่าสตริงทั้งหมด
ข้อจำกัด: สมมติคั่นด้วย Space เดียว | หากมีหลาย Space ติดกัน ต้อง TRIM() หรือ REPLACE() ก่อน