我无法理解如何将 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/