我查找了几种通过SELECT更新多列的方法,但仍然无法使其工作。这就是我试过的:
delimiter @@
CREATE TRIGGER trigger_sales
AFTER INSERT ON orders
FOR EACH ROW
BEGIN
UPDATE sales
SET (userid, productid, transaction, price, quarter) =
SELECT userid, productid, COUNT(productid) AS transaction, SUM(total_P) AS price,
case when (month(date)) >=3 and (month(date)) <=5 then 'Spring'
when (month(date)) >=6 and (month(date)) <=8 then 'Summer'
when (month(date)) >=9 and (month(date)) <=11 then 'Fall'
else 'Winter'
end AS quarter
FROM orders
GROUP BY userid, productid, quarter
END@@
delimiter;
谢谢!
答案 0 :(得分:4)
我喜欢这样做的首选方法是执行INSERT查询,确保每个插入都有一个已经使用的主键。然后我添加ON DUPLICATE KEY UPDATE
,浏览`column`=VALUES(`column`)
形式的所有字段,这样就可以了。这通常适用于外键。
答案 1 :(得分:3)
我在没有任何样本数据的情况下测试了您的查询,但此解决方案可以让您走上正确的轨道。我在多个表格上使用VIEW
时使用GROUP BY
来克服UPDATE
限制:
CREATE VIEW orders_view AS
SELECT userid,
productid,
COUNT(productid) AS 'transaction',
SUM(total_P) AS price,
CASE
WHEN (MONTH(o.date)) >=3 AND (MONTH(o.date)) <=5 THEN 'Spring'
WHEN (MONTH(o.date)) >=6 AND (MONTH(o.date)) <=8 THEN 'Summer'
WHEN (MONTH(o.date)) >=9 AND (MONTH(o.date)) <=11 THEN 'Fall'
ELSE 'Winter'
END AS quarter
FROM orders
GROUP BY userid, productid, quarter;
UPDATE sales s, orders_view o
SET s.userid = o.userid,
s.productid = o.productid,
s.`transaction` = o.`transaction`,
s.price = o.price,
s.quarter = o.quarter
WHERE s.userid = o.userid;
请注意,我没有使用真实数据对其进行测试。
更多信息:
UPDATE
Syntax