我有一个名为
的表此处的ID是主键自动递增。
我还添加了由列dateid,customerid和salesid组成的唯一约束
我的要求:每天使用我的SP插入/更新数据。
我的问题:我尝试在重复键更新上使用插入...,但无法正常工作。
我的完整代码在这里
-- this is creation script for factsales table
CREATE TABLE FactSales
(
ID BIGINT(20) NOT NULL auto_increment,
DateID INT(11) DEFAULT NULL,
CustomerID INT(11) DEFAULT NULL,
salesID INT(11) DEFAULT NULL,
salescount INT(11) DEFAULT NULL,
PRIMARY KEY (ID)
);
-- adding the unique constraint
ALTER TABLE FactSales ADD UNIQUE KEY uk1 (dateid,customerid,salesid);
-- creating the dummy table for work
DROP TABLE if exists tmpfactsales CREATE TABLE tmpfactsales
(
ID BIGINT(20) NOT NULL auto_increment,
DateID INT(11) DEFAULT NULL,
CustomerID INT(11) DEFAULT NULL,
salesID INT(11) DEFAULT NULL,
salescount INT(11) DEFAULT NULL,
PRIMARY KEY (ID)
);
-- now I need to get maximum of minimum last entry date of all customers
SELECT MIN(maxdate) INTO @MinMaxDateID
FROM (SELECT a.customerid,
MAX(a.dateid) AS maxdate
FROM factsales a
GROUP BY a..customerID) a;
-- inserting data from min max date into dummy table
INSERT INTO tmpfactsales
(
dateid,
customerid,
salesid,
Salescount
)
SELECT dateid,
customerid,
salesid,
SUM(salescount) AS salescount
FROM fact_customer_sales
WHERE status = 'active'
-- condition for daily data
AND dateid >= @minmaxdateid
AND dateid <= curdate()
GROUP BY dateid,
customerid,
salesid;
-- BEGIN Insert update on duplicate key
INSERT INTO FactSales
(
dateid,
customerid,
salesid,
salescount
)
SELECT dateid,
customerid,
salesid,
salescount
FROM tmpfactsales ON duplicate KEY UPDATE factsales.salescount = tmpfactsales.salescount;
预期结果:更新(如果已存在)或在事实销售表中插入新数据。在我的情况下,将添加新记录。
有关我的数据的更多详细信息,这里:https://i.stack.imgur.com/8myHO.png
答案 0 :(得分:1)
我无法重现您的问题
drop table if exists t,t1;
create table t (ID int auto_increment primary key , dateid date, customerid int, salesid int, salescount int);
create table t1 (ID int, dateid date, customerid int, salesid int, salescount int);
alter table t
add unique key uk1(dateid,customerid,salesid);
insert into t1 values
(1,'2019-04-11',1,1,1),
(1,'2019-04-11',1,1,2);
Insert into t
(
dateid,
customerid,
salesid,
salescount
)
select dateid,
customerid,
salesid,
salescount
from t1 -- this is the temp table that has daily data
where t1.salescount = 1
on duplicate key update t.salescount = t1.salescount;
Insert into t
(
dateid,
customerid,
salesid,
salescount
)
select dateid,
customerid,
salesid,
salescount
from t1 -- this is the temp table that has daily data
where salescount = 2
on duplicate key update t.salescount = t1.salescount;
select * from t;
+----+------------+------------+---------+------------+
| ID | dateid | customerid | salesid | salescount |
+----+------------+------------+---------+------------+
| 1 | 2019-04-11 | 1 | 1 | 2 |
+----+------------+------------+---------+------------+
1 row in set (0.00 sec)
如果这不能很好地表示您的数据,请扩展您的问题以包括表定义和一些示例数据。
答案 1 :(得分:0)
我的问题已经解决。我创建了新表,并以某种方式将其用于重复键更新。不知道为什么会首先导致问题。