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

MySQL: SELECT อีเมลขึ้นต้น 5 ตัวเลขด้วย REGEXP


คำอธิบาย

ใช้ REGEXP '^[0-9]{5}' ค้นหาอีเมลที่ขึ้นต้นด้วยตัวเลข 5 หลักติดกัน

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

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

การเพิ่มข้อมูล

mysql> insert into DemoTable values('6574John@gmail.com'); 
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('Carol23456@gmail.com'); 
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('98989Chris_45678@gmail.com'); 
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Mike12@gmail.com'); 
Query OK, 1 row affected (0.43 sec)
mysql> insert into DemoTable values('56453Adam@gmail.com'); 
Query OK, 1 row affected (0.20 sec)

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

mysql> select * from DemoTable;

ผลลัพธ์:

+----------------------------+
| UserEmailAddress           |
+----------------------------+
| 6574John@gmail.com         |
| Carol23456@gmail.com       |
| 98989Chris_45678@gmail.com |
| Mike12@gmail.com           |
| 56453Adam@gmail.com        |
+----------------------------+
5 rows in set (0.00 sec)

คิวรี่ REGEXP หาอีเมลขึ้นต้น 5 ตัวเลข

mysql> select * from DemoTable 
where UserEmailAddress REGEXP '^[0-9]{5}';

ผลลัพธ์

+----------------------------+
| UserEmailAddress           |
+----------------------------+
| 98989Chris_45678@gmail.com |
| 56453Adam@gmail.com        |
+----------------------------+
2 rows in set (0.00 sec)

คำอธิบาย Regex Pattern

  • ^: เริ่มต้นสตริง
  • [0-9]: ตัวเลข 0-9
  • {5}: จำนวน 5 ตัวติดกัน
  • ^[0-9]{5}: ขึ้นต้นด้วยตัวเลข 5 หลัก

การวิเคราะห์ข้อมูล

Emailขึ้นต้น 5 ตัวเลข?เหตุผล
6574John@gmail.comไม่มีแค่ 4 ตัว (6574)
Carol23456@gmail.comไม่ขึ้นต้น C (ตัวอักษร)
98989Chris_45678@gmail.comใช่ขึ้นต้น 98989 (5 ตัว)
Mike12@gmail.comไม่ขึ้นต้น M
56453Adam@gmail.comใช่ขึ้นต้น 56453 (5 ตัว)

REGEXP Pattern อื่นๆ สำหรับ Email

-- อีเมลที่มีตัวเลขอย่างน้อย 1 ตัว
WHERE Email REGEXP '[0-9]'

-- อีเมลที่มีตัวเลขติดกัน 3 ตัวขึ้นไป
WHERE Email REGEXP '[0-9]{3,}'

-- อีเมล Gmail
WHERE Email REGEXP '@gmail\\.com$'