MySQL中的ORDERBY字?

要在MySQL中按单词排序,您需要使用ORDER BY FIELD()。让我们首先创建一个表-

mysql> create table DemoTable
(
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentFirstName varchar(20),
   StudentFavouriteSubject varchar(100)
);

使用插入命令在表中插入一些记录-

mysql> insert into DemoTable(StudentFirstName,StudentFavouriteSubject) values('Larry','Java');

mysql> insert into DemoTable(StudentFirstName,StudentFavouriteSubject) values('Sam','C');

mysql> insert into DemoTable(StudentFirstName,StudentFavouriteSubject) values('Bob','MongoDB');

mysql> insert into DemoTable(StudentFirstName,StudentFavouriteSubject) values('David','MySQL');

使用select语句显示表中的所有记录;

mysql> select *from DemoTable;

这将产生以下输出-

+-----------+------------------+-------------------------+
| StudentId | StudentFirstName | StudentFavouriteSubject |
+-----------+------------------+-------------------------+
|         1 | Larry            | Java                    |
|         2 | Sam              | C                       |
|         3 | Bob              | MongoDB                 |
|         4 | David            | MySQL                   |
+-----------+------------------+-------------------------+
4 rows in set (0.00 sec)

以下是对MySQL中的单词ORDER BY的查询-

mysql> select *from DemoTable
ORDER BY FIELD(`StudentFavouriteSubject`, 'MongoDB','MySQL','Java','C');

这将产生以下输出-

+-----------+------------------+-------------------------+
| StudentId | StudentFirstName | StudentFavouriteSubject |
+-----------+------------------+-------------------------+
|         3 | Bob              | MongoDB                 |
|         4 | David            | MySQL                   |
|         1 | Larry            | Java                    |
|         2 | Sam              | C                       |
+-----------+------------------+-------------------------+
4 rows in set (0.03 sec)