我的数据库中有一个products
表,其中包含列/字段:
现在,我想要实现的是:
products
表中添加新值时,新输入的“productname”和“supplier”值将比较products
表中现有的所有值。方案:
products
表中已存在新的产品名称和供应商值,则新值的数量将添加到现有值的数量products
表。继承了尝试过的代码,但它不起作用:
Delimiter //
CREATE PROCEDURE `wew`(pid int,pname varchar(50),pdesc varchar(50),psupp varchar(50),pdate date,pquant int)
begin
declare lloyd char default null;
select productname from products where productname=pname LIMIT 1 into lloyd for update;
if(lloyd) then
update products set quantityleft=quantityleft+pquant where productname=pname;
else
insert into products (productid,productname,proddescription,supplier,lastpurchasedate,quantityleft) values(pid,pname,pdesc,psupp,pdate,pquant);
end if;
end;
//
你能帮忙解决这个问题吗?真的很困惑。
DESC产品:
SQL result
Host: localhost
Database: prodpurchase
Generation Time: Mar 24, 2013 at 03:52 PM
Generated by: phpMyAdmin 3.2.4 / MySQL 5.1.41
SQL query: Desc Products;
Rows: 7
Field Type Null Key Default Extra
ProdID int(5) NO PRI NULL auto_increment
ProdName varchar(50) NO UNI NULL
ProdSupplier varchar(250) NO UNI NULL
ProdDescription varchar(250) NO NULL
ProdDate date NO NULL
ProdPrice double NO 0
ProdQuantity int(50) NO NULL
答案 0 :(得分:2)
您可以利用MySQL的 INSERT...ON DUPLICATE KEY UPDATE
首先,您需要添加UNIQUE
约束列:productname
和supplier
:
ALTER TABLE products ADD CONSTRAINT tb_uq UNIQUE (productname, supplier)
执行完毕后,
INSERT INTO products (productid, productname, proddescription, supplier, lastpurchasedate, quantityleft)
VALUES (pid, pname, pdesc, psupp, pdate, pquant)
ON DUPLICATE KEY UPDATE quantityleft = quantityleft + pquant;