此查询计算总和p_quantity <= 21000
为p_description
。查询工作,但是当你添加ORDER BY p_reference
显示所有行如何在MySQL中使用ORDER BY使用变量SET
我尝试添加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);
我不明白这个问题。你想要点什么?它在我看来你在发布的查询中使用ORDER BY,那有什么问题? – Jaylen 2014-12-06 19:19:42
当您添加ORDER BY p_reference显示所有行并且p_quantity> 21000时,但没有添加ORDER BY p_reference时,总p_quantity <= 21000 – phptraining 2014-12-06 20:00:53
此问题比它看起来更难。事实上,我投票你的问题给我一个挑战:)请检查我的答案 – Jaylen 2014-12-06 21:54:28