我在MySQL中使用带有'order by'条件子句的预准备语句。用'?'并且变量不能用于订购之类的东西,所以我决定以其他方式制作它。我设置条件,但它是更多的代码。也许还有其他选择来减少代码并只是改变'order by'参数?
IF sorting_column_index = 1 and sorting_column_mode = 0
THEN PREPARE STMT FROM 'SELECT a.oid as \'oid\',
...
FROM table as a
...
order by numero_annee desc LIMIT ?, ?';
EXECUTE STMT USING @skip, @ROWS;
END IF;
IF sorting_column_index = 2 and sorting_column_mode = 1
THEN PREPARE STMT FROM 'SELECT a.oid as \'oid\',
...
FROM table as a
...
order by numero_ordre asc LIMIT ?, ?';
EXECUTE STMT USING @skip, @ROWS;
END IF;
...
答案 0 :(得分:2)
尝试这样的事情,不使用asc / desc的参数,而是构建查询字符串:
SET @sort_order = 'desc';
SET @my_limit = 5;
SET @sql = CONCAT('SELECT whatever FROM whatever ORDER BY col1 ', @sort_order, ' LIMIT ?;');
PREPARE stmt FROM @sql;
EXECUTE stmt USING @my_limit;
DEALLOCATE PREPARE stmt;