MySQL ORDER BY 使用数字用户定义变量?

mysqlmysqli database

首先我们创建一个表 −

mysql> create table DemoTable1898
   (
   Number int
   );
Query OK, 0 rows affected (0.00 sec)

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

mysql> insert into DemoTable1898 values(10);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1898 values(70);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1898 values(30);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1898 values(50);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1898 values(40);
Query OK, 1 row affected (0.00 sec)

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

mysql> select * from DemoTable1898;

这将产生以下输出 −

+--------+
| Number |
+--------+
|     10 |
|     70 |
|     30 |
|     50 |
|     40 |
+--------+
5 rows in set (0.00 sec)

这是使用数字用户定义变量执行 ORDER BY 的查询 −

mysql> set @limitValue:=1;
Query OK, 0 rows affected (0.00 sec)
mysql> set  @query:=CONCAT('select * from DemoTable1898 order by ',@limitValue);
Query OK, 0 rows affected (0.00 sec)
mysql> prepare stmt from @query;
Query OK, 0 rows affected (0.00 sec)
Statement prepared
mysql> execute stmt;

这将产生以下输出 −

+--------+
| Number |
+--------+
|     10 |
|     30 |
|     40 |
|     50 |
|     70 |
+--------+
5 rows in set (0.00 sec)

这是解除准备查询的查询 −

mysql> deallocate prepare stmt;
Query OK, 0 rows affected (0.00 sec)

相关文章