MySQL 中的 ORDERBY word 是什么?
要通过 word 在 MySQL 中排序,你需要使用 ORDER BY FIELD()。我们首先创建一个表 −
mysql> create table DemoTable ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentFirstName varchar(20), StudentFavouriteSubject varchar(100) ); Query OK, 0 rows affected (0.52 sec)
使用 insert 命令在表中插入一些记录 −
mysql> insert into DemoTable(StudentFirstName,StudentFavouriteSubject) values('Larry','Java'); Query OK, 1 row affected (0.12 sec) mysql> insert into DemoTable(StudentFirstName,StudentFavouriteSubject) values('Sam','C'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(StudentFirstName,StudentFavouriteSubject) values('Bob','MongoDB'); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable(StudentFirstName,StudentFavouriteSubject) values('David','MySQL'); Query OK, 1 row affected (0.17 sec)
使用 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 word 查询 −
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)
广告