使用存储过程求和、分组并插入到另一个 table 中

USING STORED PROCEDURE to SUM, GROUP BY and insert to another table with

我创建了 3 个 table:itemshopstock。加上一个名为 inserting 的存储过程 它使用 item table

中的给定项目插入 shop table
CREATE TABLE item(
i_id int(11) auto_increment,
i_name varchar(255) not null,
primary key(i_id));

CREATE TABLE shop(
s_id     int(11) auto_increment,
s_name   varchar(255) not null,
s_item   int(11) not null,
s_qty    int(11) not null,
primary  key(s_id),
foreign  key(s_item) references item(i_id)
);

CREATE TABLE stock(
item     int(11) not null,
total    int(11) not null
);

CREATE PROCEDURE inserting (
IN shop_name varchar(225),
IN shop_item int(11),
IN shop_qty int(11)
)

BEGIN

INSERT INTO shop(s_name, s_item, s_qty) 
VALUES
(shop_name, shop_item, shop_qty);

INSERT INTO STOCK(item, total) 
SELECT s_item, SUM(s_qty) FROM shop GROUP BY s_item
ON DUPLICATE KEY UPDATE
item = VALUES(item),
total = VALUES(total);

第一个插入有效,但在第二个插入中填充 stock table 时,它给了我额外的列,这是我没有预料到的。

我已经尝试使用 REPLACE INTO 和 ON DUPLICATE KEY UPDATE 来获得单个结果,结果仍然如下:

SELECT * FROM `stock`;
+------+-------+
| ITEM | TOTAL |
+------+-------+
|    1 |     5 |
|    1 |     9 |
+------+-------+

我想要实现的是,将 ITEM 列分组,并将 TOTAL 汇总到一行。

我在这里做错了什么,或者查询中遗漏了什么?

谢谢。

要使 on duplicate key 语法按预期工作,您需要对目标 table 进行唯一或主键约束,以便数据库可以识别“重复”行。 REPLACE 语法也是如此。

但是你的stocktable没有主键。请考虑以下 DDL:

CREATE TABLE stock(
    item     int(11) primary key,
    total    int(11) not null
);

旁注:无需在 on duplicate key 子句中重新分配列 item,因为它首先用于识别冲突。这已经足够好了:

INSERT INTO STOCK(item, total) 
SELECT s_item, SUM(s_qty) FROM shop GROUP BY s_item
ON DUPLICATE KEY UPDATE total = VALUES(total);

如果你 运行 这一次,它应该会像你预期的那样工作。但是由于@gmb 所说的,随后的 运行s 可能会带来重复的 ITEM。 table 必须有一个 UNIQUE indexPRIMARY KEY。在此处查看更多详细信息

https://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html