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

จัดเรียงสตริงที่มี Underscore ใน MySQL ให้ John_ อยู่บนสุด

เมื่อต้องการจัดเรียงสตริงโดยให้รูปแบบเฉพาะ (เช่นขึ้นต้นด้วย 'John_') อยู่บนสุด สามารถใช้เงื่อนไข Boolean ใน ORDER BY ได้

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

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

เพิ่มข้อมูลชื่อต่างๆ

mysql> insert into DemoTable values('John_Smith'); 
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Chris Brown'); 
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable values('John_Doe'); 
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('David Miller'); 
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values('Carol Taylor'); 
Query OK, 1 row affected (0.13 sec)

แสดงข้อมูลก่อนจัดเรียง

mysql> select * from DemoTable;
+--------------+
| Name         |
+--------------+
| John_Smith   |
| Chris Brown  |
| John_Doe     |
| David Miller |
| Carol Taylor |
+--------------+
5 rows in set (0.00 sec)

คำสั่ง ORDER BY ให้ John_ อยู่บนสุด แล้วสุ่มที่เหลือ

mysql> select * from DemoTable 
order by (Name LIKE 'John_%') DESC, rand();

ผลลัพธ์ (John_ อยู่บนสุด 2 แถว แล้วสุ่มอันอื่น)

+--------------+
| Name         |
+--------------+
| John_Doe     |
| John_Smith   |
| Carol Taylor |
| David Miller |
| Chris Brown  |
+--------------+
5 rows in set (0.42 sec)

คำอธิบาย: (Name LIKE 'John_%') คืนค่า 1 (TRUE) สำหรับชื่อที่ขึ้นต้นด้วย 'John_' และ 0 (FALSE) สำหรับอื่นๆ เรียง DESC ทำให้ TRUE อยู่บนสุด rand() ใช้สุ่มลำดับของกลุ่มที่เหลือ

ประยุกต์ใช้: ใส่โปรโมชั่น/สินค้าแนะนำไว้บนสุด แล้วสุ่มสินค้าอื่นๆ