Computer >> Máy Tính >  >> Lập trình >> MySQL

Truy vấn MySQL để đặt một bản ghi cụ thể lên trên cùng

Đối với điều này, bạn có thể sử dụng câu lệnh ORDER BY CASE. Đầu tiên chúng ta hãy tạo một bảng -

mysql> create table DemoTable
(
   StudentName varchar(100),
   StudentMarks int
);
Query OK, 0 rows affected (0.97 sec)

Chèn một số bản ghi vào bảng bằng lệnh chèn -

mysql> insert into DemoTable values('Chris',45);
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values('John',67);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('David',89);
Query OK, 1 row affected (0.46 sec)
mysql> insert into DemoTable values('John',98);
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values('Mike',79);
Query OK, 1 row affected (0.12 sec)
mysql> insert into DemoTable values('John',99);
Query OK, 1 row affected (0.11 sec)

Hiển thị tất cả các bản ghi từ bảng bằng câu lệnh select -

mysql> select *from DemoTable;

Điều này sẽ tạo ra kết quả sau -

+-------------+--------------+
| StudentName | StudentMarks |
+-------------+--------------+
| Chris       |           45 |
| John        |           67 |
| David       |           89 |
| John        |           98 |
| Mike        |           79 |
| John        |           99 |
+-------------+--------------+
6 rows in set (0.00 sec)

Sau đây là truy vấn để đặt một bản ghi cụ thể lên trên cùng -

mysql> select *from DemoTable order by case StudentName when 'John' then 2 else 3 end, StudentName, StudentMarks;

Điều này sẽ tạo ra kết quả sau -

+-------------+--------------+
| StudentName | StudentMarks |
+-------------+--------------+
| John        |           67 |
| John        |           98 |
| John        |           99 |
| Chris       |           45 |
| David       |           89 |
| Mike        |           79 |
+-------------+--------------+
6 rows in set (0.00 sec)