mysql - 如何使用变量 SET 在 MySQL 中使用 ORDER BY

标签 mysql variables filter sql-order-by rows

此查询用于计算总和 p_quantity <= 21000对于 p_description .该查询有效,但是当您添加 ORDER BY p_reference 时显示所有行

我尝试添加 ORDER BY像这样:

SET @runtot:=0;
SELECT p_id, p_description, (@runtot := @runtot + p_quantity) AS runningTotal
FROM product_table
WHERE @runtot + p_quantity <= 21000 AND p_description = 'product_1' ORDER BY p_reference ASC

这是创建产品表的代码:

CREATE TABLE IF NOT EXISTS `product_table` (
  `p_id` int(11) PRIMARY KEY AUTO_INCREMENT NOT NULL,
  `p_description` varchar(50) NOT NULL,
  `p_reference` varchar(25) NOT NULL,
  `p_location` varchar(25) NOT NULL,
  `p_quantity` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

INSERT INTO `product_table` (`p_id`, `p_description`, `p_reference`, `p_location`, `p_quantity`) VALUES
  (1, 'Product_1', '1A00001', 'AP07', 7000),
  (2, 'Product_1', '1A00001', 'AF05', 6000),
  (3, 'Product_1', '1A00233', 'DS07', 7000),
  (4, 'Product_1', '1A00233', 'SD10', 5000),
  (5, 'Product_1', '1A00001', 'YB12', 7000),
  (6, 'Product_1', '1A00001', 'AN01', 7000),
  (7, 'Product_1', '1A00001', 'AP04', 7000),
  (8, 'Product_1', '1A00245', 'AP01', 7000),
  (9, 'Product_1', '1A00001', 'QD01', 7000),
  (10, 'Product_1', '1A00001', 'SC01', 7000);

最佳答案

因为您没有在查询中选择p_reference。试试看,

SET @runtot:=0;
SELECT p_id, p_description, **p_reference**, (@runtot := @runtot + p_quantity) AS runningTotal
FROM product_table
WHERE @runtot + p_quantity <= 21000 AND p_description = 'product_1'
ORDER BY p_reference ASC;

关于mysql - 如何使用变量 SET 在 MySQL 中使用 ORDER BY,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27335294/

相关文章:

mysql - 如何创建从不同服务器和数据库读取数据的 MySQL View ?

mysql - 选择mysql中重复的字段

java - 使用 JFileChooser 选择文件扩展名

hadoop - 如何在 pig latin 中的 foreach 中使用过滤器运算符

javascript - 如何在 javascript 中向数组添加新的键和值?

mysql - 无法使用命令行连接到 MySQL,但可以使用 MySQL Workbench

php - 使用几个选项过滤 php mysql

Javascript setInterval 不更新内部使用的时间戳

c - 如何将浮点变量从一个函数传递到另一个函数?

javascript - 有没有办法在JS中将 "subproperties"添加到变量中?