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


我们首先创建一个表 −

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

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

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)

更新于: 27-12-2019

307 次浏览

启动您 职业

通过完成课程获取认证

开始
广告