2

我查找了几种通过 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;

谢谢!

4

2 回答 2

4

我喜欢做这样的事情的方法是做一个 INSERT 查询,确保每个插入都有一个已经被使用的主键。然后我添加ON DUPLICATE KEY UPDATE,浏览表单中的所有字段,`column`=VALUES(`column`)这很好。这通常在外键到位的情况下效果最好。

于 2013-05-27T01:54:56.760 回答
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;

请注意,我没有使用真实数据对其进行测试。

更多信息:

于 2013-05-27T01:57:49.750 回答