我有一种情况,请考虑以下问题:
select
A.cakename, A.status, B.ordertime
from
Cake as A
inner join
Orders as B on A.cakeid = B.cakeid
此查询的输出
cakename, status, ordertime
Apple Pie, available, 2014-03-20 22:34:46
Apple Pie, available, 2014-10-10 04:00:00
Apple Pie, available, 2015-03-20 22:34:46
Brownie, available, 2014-03-20 22:35:07
Brownie, available, 2015-05-20 22:35:07
Brownie, available, 2014-03-26 22:36:07
Brownie, available, 2015-05-20 14:35:48
Brownie, available, 2015-05-20 22:35:07
Brownie, available, 2015-05-10 22:35:07
现在我想减去ordertime row n+1 - ordertime row n
并创建一个单独的列来存储结果。现在你可以忽略最后一行,因为没有下一行。
例如:2014-10-10 04:00:00
- 2014-03-20 22:34:46
此等式将用于第一行,其结果将存储在新列中,我们可以使用difference of consecutive ordertime
。谁能给我一些解决这种情况的指示?
如果你可以帮助创建一个很棒的auto increment column
,那么我可以自己加入并采取不同的行动。
答案 0 :(得分:2)
您可以添加额外的计算字段:
select
A.cakename, A.status, B.ordertime,
(SELECT MAX(ordertime) FROM Orders AS C WHERE C.ordertime < B.ordertime) AS prev
from
Cake as A
inner join
Orders as B on A.cakeid = B.cakeid
ORDER BY ordertime;
但您最好在ordertime
上找到索引:
CREATE INDEX ord_ndx ON Orders(ordertime, cakeid);
实际上,您可以直接计算the difference from the previous time(假设它不是NULL;您必须提供带有IF的默认值)。
但是,根据您的体系结构,您可以通过添加列(previous_order
)来获得更好的服务。当您插入订单时,您就知道自己需要什么。使用TRIGGER
:
CREATE TABLE test ( itemid integer, ordertime timestamp, previous datetime );
CREATE INDEX test_ndx ON test (itemid, ordertime);
CREATE TRIGGER test_set_prev
BEFORE INSERT ON test
FOR EACH ROW
SET NEW.previous = (
SELECT MAX(ordertime) FROM test WHERE itemid = NEW.itemid
);
现在您的表格会自动生效。 TIMESTAMP列将自动更新,previous
列也将自动更新:
insert into test (itemid) values (2);
select sleep(2);
insert into test (itemid) values (2);
+--------+---------------------+---------------------+
| itemid | ordertime | previous |
+--------+---------------------+---------------------+
| 2 | 2015-10-21 09:30:44 | NULL |
| 2 | 2015-10-21 09:30:46 | 2015-10-21 09:30:44 |
+--------+---------------------+---------------------+
它也适用于多个插入:
insert into test (itemid) values (3), (2), (3);
答案 1 :(得分:2)
SELECT t.*,
IF(@prev IS NULL ,0 , TIMESTAMPDIFF(SECOND,t.ordertime,@prev)) diff,
@prev = t.ordertime
FROM (
SELECT
A.cakename, A.status, B.ordertime
FROM Cake as A
INNER JOIN Orders as B
ON A.cakeid = B.cakeid
ORDER BY ordertime
) t