คำอธิบาย
ใช้ NOT LIKE '% %' เพื่อกรองเฉพาะแถวที่ไม่มีช่องว่าง (Space) หมายถึงเป็นคำเดียว (Single word)
ขั้นตอนการสร้างตารางและข้อมูลตัวอย่าง
mysql> create table DemoTable (
Name varchar(50) );
Query OK, 0 rows affected (0.50 sec)
การเพิ่มข้อมูล
mysql> insert into DemoTable values('John Smith');
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('John');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Adam Smith');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('Carol');
Query OK, 1 row affected (0.10 sec)
mysql> insert into DemoTable values('David Miller');
Query OK, 1 row affected (0.10 sec)
แสดงข้อมูลทั้งหมด
mysql> select * from DemoTable;
ผลลัพธ์:
+--------------+ | Name | +--------------+ | John Smith | | John | | Adam Smith | | Carol | | David Miller | +--------------+ 5 rows in set (0.00 sec)
คิวรี่กรองเฉพาะคำเดียว
mysql> select * from DemoTable where Name not like '% %';
ผลลัพธ์
+-------+ | Name | +-------+ | John | | Carol | +-------+ 2 rows in set (0.00 sec)
คำอธิบาย
- LIKE '% %': ตรงกับสตริงที่มีช่องว่างอย่างน้อย 1 ตัว
- NOT LIKE '% %': ตรงกับสตริงที่ ไม่มี ช่องว่างเลย
- John Smith, Adam Smith, David Miller มีช่องว่าง จึงถูกกรองออก
ขยายความ: ใช้ REGEXP
วิธีอื่นที่ยืดหยุ่นกว่า:
select * from DemoTable where Name NOT REGEXP ' '; -- ไม่มี space select * from DemoTable where Name REGEXP '^[^ ]+$'; -- ไม่มี space ทั้งสตริง