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

ดึงตัวอักษร 15 ตัวแรกจากคอลัมน์สตริงใน MySQL ด้วย SUBSTR

ฟังก์ชัน SUBSTR() (หรือ SUBSTRING()) ใน MySQL ใช้ดึงส่วนของสตริง ตามตำแหน่งและความยาวที่กำหนด

ตัวอย่างการสร้างตาราง

mysql> create table DemoTable ( 
    Title varchar(100) ); 
Query OK, 0 rows affected (0.69 sec)

เพิ่มข้อมูลข้อความยาว

mysql> insert into DemoTable values('Introduction to MySQL'); 
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values('Introduction to Java'); 
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable values('C in Depth with data structure and algorithm'); 
Query OK, 1 row affected (0.15 sec)

แสดงข้อมูลทั้งหมด

mysql> select * from DemoTable;
+----------------------------------------------+
| Title                                        |
+----------------------------------------------+
| Introduction to MySQL                        |
| Introduction to Java                         |
| C in Depth with data structure and algorithm |
+----------------------------------------------+
3 rows in set (0.00 sec)

คำสั่งดึง 15 ตัวอักษรแรก

mysql> select substr(Title, 1, 15) from DemoTable;

ผลลัพธ์

+--------------------+
| substr(Title,1,15) |
+--------------------+
| Introduction to    |
| Introduction to    |
| C in Depth with    |
+--------------------+
3 rows in set (0.00 sec)

รูปแบบการใช้งาน:

  • SUBSTR(str, pos) - ดึงตั้งแต่ตำแหน่ง pos ถึงท้ายสตริง
  • SUBSTR(str, pos, len) - ดึงตั้งแต่ตำแหน่ง pos ยาว len ตัวอักษร
  • SUBSTR(str, -len) - ดึง len ตัวอักษรสุดท้าย (ตำแหน่งลบ = นับจากท้าย)

หมายเหตุ: ตำแหน่งใน MySQL เริ่มที่ 1 (ไม่ใช่ 0 เหมือนภาษาโปรแกรมส่วนใหญ่)