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

วิธีดึงข้อความ 40 ตัวอักษรแรกจากฟิลด์ TEXT ใน MySQL

การใช้ฟังก์ชัน LEFT()

ฟังก์ชัน LEFT() ใช้ดึงตัวอักษรจากด้านซ้าย (จุดเริ่มต้น) ของสตริง จำนวนที่กำหนด

รูปแบบคำสั่ง

SELECT LEFT(yourColumnName, 40) AS anyVariableName FROM yourTableName;

ตัวอย่างการสร้างตารางและข้อมูล

mysql> CREATE TABLE retrieveFirst40Characters (
    -> AllWords TEXT
    -> );
Query OK, 0 rows affected (0.59 sec)

mysql> INSERT INTO retrieveFirst40Characters VALUES('This is a demo text displayed in a table for our example');

ข้อมูลต้นฉบับ

mysql> SELECT * FROM retrieveFirst40Characters;
+------------------------------------------------------------------------------------------------------------------------+
| AllWords                                                                                                                 |
+------------------------------------------------------------------------------------------------------------------------+
| This is a demo text displayed in a table for our example                                                                 |
+------------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

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

mysql> SELECT LEFT(AllWords, 40) AS Retrieve40Characters FROM retrieveFirst40Characters;
+------------------------------------------+
| Retrieve40Characters                     |
+------------------------------------------+
| This is a demo text displayed in a table |
+------------------------------------------+
1 row in set (0.03 sec)

ฟังก์ชันเกี่ยวข้อง:

  • RIGHT(str, n) - ดึง n ตัวอักษรจากด้านขวา
  • SUBSTRING(str, pos, len) - ดึงจากตำแหน่งที่กำหนด
  • SUBSTRING_INDEX(str, delim, count) - ดึงส่วนก่อน/หลัง delimiter

การใช้งานจริง: เหมาะสำหรับสร้าง preview/summary ของบทความหรือเนื้อหายาว