【发布时间】:2014-01-04 13:29:42
【问题描述】:
见this sqlfiddle(如果小提琴将来死了,也会在下面)。目标是将所有已签出的商品返回到 items 表,更新数量值。
CREATE TABLE checkout(
id INT NOT NULL
-- toUser, indexes, etc
);
CREATE TABLE inventory(
id INT NOT NULL AUTO_INCREMENT,
quantity INT DEFAULT 0,
PRIMARY KEY (id)
);
INSERT INTO inventory(quantity) VALUES(90);
INSERT INTO inventory(quantity) VALUES(42);
-- 10 values
INSERT INTO checkout(id) VALUES(1),(1),(1),(1),(1),(1),(1),(1),(1),(1);
-- 8 values
INSERT INTO checkout(id) VALUES(2),(2),(2),(2),(2),(2),(2),(2);
-- Return all the checked out items back to the inventory (up the quantity)
UPDATE inventory i
INNER JOIN checkout c ON c.id = i.id
SET i.quantity = i.quantity + 1;
在这次更新之后,我期待这个结果:
Inventory:
id = 1, quantity = 100
id = 2, quantity = 50
相反,收到的是:
Inventory:
id = 1, quantity = 91
id = 2, quantity = 43
一个连接返回 18 行:
SELECT * FROM inventory i INNER JOIN checkout c ON c.id = i.id;
我认为我对 UPDATE 操作的理解存在漏洞。感谢您的帮助。
【问题讨论】:
-
所以问题是你为什么期望 100 和 50?JOIN 是 ON ID,库存中只有 2 个不同的 id,所以 90+1 和 42+1。
-
@Mihai 将 SELECT 的 UPDATE 替换为
SELECT * FROM inventory i INNER JOIN checkout c ON c.id = i.id,生成我正在寻找的所有行。然后,我期望沿着行走。根据@eggyal,这种行为本质上是未定义的,就像你提到的那样看起来像 DISTINCT。谢谢-
标签: mysql sql sql-update