查找 MySQL 中记录之间的变化
finding change between records in MySQL
我有一个 table,我在其中存储许多坦克内存储的桶数。我每晚午夜以及任何操作员发起的传输的开始和结束时都在这里存储值。
我想要 return 是自该特定坦克的上次事件记录以来的桶数差异。我有正确的自连接 ID 来获取以前的记录号,但是桶不正确。
这是我目前拥有的。
SELECT
inventory.id,
MAX(inventory2.id) AS id2,
inventory.tankname,
inventory.barrels,
inventory.eventstamp,
inventory2.barrels
FROM
inventory
LEFT JOIN
inventory inventory2 ON inventory2.tankname = inventory.tankname AND inventory2.eventstamp < inventory.eventstamp
GROUP BY
inventory.id,
inventory.tankname,
inventory.barrels,
inventory.eventstamp
ORDER BY
inventory.tankname,
inventory.eventstamp
return以下
只使用相关子查询:
SELECT i.*,
(SELECT i2.id
FROM inventory i2
WHERE i2.tankname = i.tankname AND
i2.eventstamp < i.eventstamp
ORDER BY i2.eventstamp DESC
LIMIT 1
) as prev_id,
(SELECT i2.barrels
FROM inventory i2
WHERE i2.tankname = i.tankname AND
i2.eventstamp < i.eventstamp
ORDER BY i2.eventstamp DESC
LIMIT 1
) as prev_barrels
FROM inventory i
ORDER BY i.tankname, i.eventstamp;
您的查询不起作用,因为您在 SELECT
中有不在 GROUP BY
中的列,并且未聚合。这在任何数据库中都不应该被允许;不幸的是 MySQL 确实允许它。
我有一个 table,我在其中存储许多坦克内存储的桶数。我每晚午夜以及任何操作员发起的传输的开始和结束时都在这里存储值。
我想要 return 是自该特定坦克的上次事件记录以来的桶数差异。我有正确的自连接 ID 来获取以前的记录号,但是桶不正确。
这是我目前拥有的。
SELECT
inventory.id,
MAX(inventory2.id) AS id2,
inventory.tankname,
inventory.barrels,
inventory.eventstamp,
inventory2.barrels
FROM
inventory
LEFT JOIN
inventory inventory2 ON inventory2.tankname = inventory.tankname AND inventory2.eventstamp < inventory.eventstamp
GROUP BY
inventory.id,
inventory.tankname,
inventory.barrels,
inventory.eventstamp
ORDER BY
inventory.tankname,
inventory.eventstamp
return以下
只使用相关子查询:
SELECT i.*,
(SELECT i2.id
FROM inventory i2
WHERE i2.tankname = i.tankname AND
i2.eventstamp < i.eventstamp
ORDER BY i2.eventstamp DESC
LIMIT 1
) as prev_id,
(SELECT i2.barrels
FROM inventory i2
WHERE i2.tankname = i.tankname AND
i2.eventstamp < i.eventstamp
ORDER BY i2.eventstamp DESC
LIMIT 1
) as prev_barrels
FROM inventory i
ORDER BY i.tankname, i.eventstamp;
您的查询不起作用,因为您在 SELECT
中有不在 GROUP BY
中的列,并且未聚合。这在任何数据库中都不应该被允许;不幸的是 MySQL 确实允许它。