我需要构建一个 MYSQL VERSION 5.6.15 查询,它允许我执行一个返回一列答案的 SELECT 语句,然后使用该列来构建下一个 SELECT 语句。
我是 mySQL 的新手,尝试过很多想法,但到目前为止都失败了。我确信答案一定很简单,但我已经放弃了自己弄清楚。如果您能提供任何帮助,我们将不胜感激。
这是我可以用来证明我的困境的最简单的一组数据:
order_date quantity
'2014-01-01 00:00:00', '27'
'2014-01-02 00:00:00', '13'
'2014-01-03 00:00:00', '42'
'2014-01-04 00:00:00', '30'
'2014-01-05 00:00:00', '5'
'2014-01-06 00:00:00', '50'
'2014-01-07 00:00:00', '2'
'2014-01-08 00:00:00', '10'
'2014-01-09 00:00:00', '40'
'2014-01-10 00:00:00', '4'
'2014-01-11 00:00:00', '32'
'2014-01-13 00:00:00', '17'
'2014-01-15 00:00:00', '54'
'2014-01-17 00:00:00', '14'
'2014-01-20 00:00:00', '37'
'2014-01-22 00:00:00', '12'
我的第一个查询是这样的:
SELECT order_date, quantity
FROM orders
WHERE quantity >35
所以,我会得到这个:
order_date quantity
'2014-01-03 00:00:00', '42'
'2014-01-06 00:00:00', '50'
'2014-01-09 00:00:00', '40'
'2014-01-15 00:00:00', '54'
'2014-01-20 00:00:00', '37'
现在,我想要的下一个查询是从 order_date< 中为上述各项的 NEXT ENTRY 选择
列。 order_date
和 quantity
/
注意:日期并不总是连续的,因此 INTERVAL +1 并不总是相关的。
因此,第二个查询将返回以下行:
order_date quantity
'2014-01-04 00:00:00', '30'
'2014-01-07 00:00:00', '2'
'2014-01-10 00:00:00', '4'
'2014-01-17 00:00:00', '14'
'2014-01-22 00:00:00', '12'
理想情况下,我可以将它们与第一个查询放在一起,按日期排序。我知道它一定是某种 join
或 IN
语句,但到目前为止我还没有意识到这一点。所以,最终的解决方案将返回这个:
order_date quantity
'2014-01-03 00:00:00', '42'
'2014-01-04 00:00:00', '30'
'2014-01-06 00:00:00', '50'
'2014-01-07 00:00:00', '2'
'2014-01-09 00:00:00', '40'
'2014-01-10 00:00:00', '4'
'2014-01-15 00:00:00', '54'
'2014-01-17 00:00:00', '14'
'2014-01-20 00:00:00', '37'
'2014-01-22 00:00:00', '12'
最佳答案
这应该可以解决问题。这不是构建查询的最佳方式,因为它可以在非常大的表上缓慢运行……但这应该可以满足您的需求……参见 fiddle http://sqlfiddle.com/#!2/b7a53/10
SELECT
order_date as o_date,
quantity,
(SELECT order_date FROM orders WHERE order_date > o_date LIMIT 1) as next_date,
(SELECT quantity FROM orders WHERE order_date > o_date LIMIT 1) as next_quantity
FROM orders
where quantity > 35
关于mysql - 如何选择一列日期并使用它来驱动第二个 SELECT 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22433422/