ใช้ SUBSTRING_INDEX() ดึงคำแรก (หรือคำสุดท้าย)
ฟังก์ชัน SUBSTRING_INDEX(str, delim, count) คืนค่าส่วนของสตริงก่อน/หลัง delimiter ตัวที่ count
รูปแบบคำสั่ง
SELECT SUBSTRING_INDEX(yourColumnName, ' ', 1) AS anyVariableName FROM yourTableName;
count > 0: ดึงส่วนซ้ายของ delimiter ตัวที่ countcount < 0: ดึงส่วนขวาของ delimiter ตัวที่ |count| นับจากท้าย
ตัวอย่างสร้างตารางและข้อมูล
mysql> CREATE TABLE FirstWordDemo (
-> AllWords LONGTEXT
-> );
Query OK, 0 rows affected (0.83 sec)
mysql> INSERT INTO FirstWordDemo VALUES('This is the first MySQL Query');
mysql> INSERT INTO FirstWordDemo VALUES('MySQL is a Relational Database');
mysql> INSERT INTO FirstWordDemo VALUES('FirstWord is not correct');
ข้อมูลทั้งหมด
mysql> SELECT * FROM FirstWordDemo;
+--------------------------------+ | AllWords | +--------------------------------+ | This is the first MySQL Query | | MySQL is a Relational Database | | FirstWord is not correct | +--------------------------------+ 3 rows in set (0.00 sec)
ดึงคำแรก (count = 1)
mysql> SELECT SUBSTRING_INDEX(AllWords, ' ', 1) AS MyFirstWordResult FROM FirstWordDemo;
+-------------------+ | MyFirstWordResult | +-------------------+ | This | | MySQL | | FirstWord | +-------------------+ 3 rows in set (0.00 sec)
ดึงคำสุดท้าย (count = -1)
SELECT SUBSTRING_INDEX(AllWords, ' ', -1) AS LastWord FROM FirstWordDemo;
+----------+ | LastWord | +----------+ | Query | | Database | | correct | +----------+ 3 rows in set (0.00 sec)
การประยุกต์ใช้:
- แยกชื่อ-นามสกุล:
SUBSTRING_INDEX(full_name, ' ', 1)= first name - แยก domain:
SUBSTRING_INDEX(email, '@', -1)= domain - แยก path:
SUBSTRING_INDEX(url, '/', -1)= filename