MySQL ORDER BY 与数字变量

标签 mysql stored-procedures

我无法理解如何将 UNSIGNED 参数传递给 MySQL 过程来继续 ORDER BY,如下所示:

DECLARE orderColumnNumber UNSIGNED;
SET orderColumnNumber = 1;

SELECT *
FROM users 
ORDER BY orderColumnNumber; 

如果我执行:

SELECT *
FROM users 
ORDER BY 1;

它可以正常工作,但使用变量则不行。

更新:

这也不起作用:

    SELECT *
    FROM users 
    ORDER BY CAST(2 AS UNSIGNED);   

最佳答案

我认为你没有捕获重点。您正在寻找的是这样的:

SELECT *
FROM users 
ORDER BY columnName    -- Here you provide the column name by which you want to sort
LIMIT orderColumnNumber ; 

即,在 ORDER BY 中,您提供希望数据排序所依据的列名称。据我了解,您想根据您声明的变量来限制您的数据。

当您在 ORDER BY 中提供 orderColumnNumber 时,它会被解释为列名称,因此它不会按您想要的方式工作。

现在的重点是为什么它适用于 ORDER BY 1 然后是 SQL standard答案如下:

10)If ORDER BY is specified, then each <sort specification> in the
        <order by clause> shall identify a column of T.

        Case:

        a) If a <sort specification> contains a <column name>, then T
          shall contain exactly one column with that <column name> and
          the <sort specification> identifies that column.

        b) If a <sort specification> contains an <unsigned integer>,
          then the <unsigned integer> shall be greater than 0 and not
          greater than the degree of T. The <sort specification> iden-
          tifies the column of T with the ordinal position specified by
          the <unsigned integer>.

编辑:

如果您想使用您评论的变量,您可以尝试如下:

SET @orderColumnNumber := 1;
SET @sql:=CONCAT('SELECT * FROM users Order BY ',@orderColumnNumber);
PREPARE dynamic_statement FROM @sql;
EXECUTE dynamic_statement;
DEALLOCATE PREPARE dynamic_statement;

关于MySQL ORDER BY 与数字变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32501009/

相关文章:

php - 抓取标签之间的信息

mysql - 如何减少 mysql 数据库中现有日期列中的一天?

mysql - 仅为单个数据库设置root无密码

mysql - 从 MYSQL 存储过程返回多个结果集

mysql - 创建存储过程 phpmyadmin 时出错

sql - 在存储过程中更改数据库名称和跨数据库查询

mysql - 合并具有一对一关系的表

php - 无法从moodle下载带有西类牙口音(áéíóú)的文件,出现403错误,但口音在页面中正确显示

mysql - 如何将 ID 列表传递给 MySQL 存储过程?

c# - Azure SQL DB 保持连接直到 EF 超时