我发现这个question与我要完成的任务几乎相同,但是在单独的表上有一个触发器,并且对于如何创建一个触发器,如果在发生以下情况时将进行UPDATE / DELETE / INSERT,则一无所知表1中添加了新产品。
表1的设置是这样的(更多列,但它们无关紧要);
product | sold
milk | 6
milk | 4
bread | 3
bread | 2
bread | 2
我想更新第二张表,其中SUM(sold) GROUP by product
和COUNT(product) GROUP by product
在第二张表上自动更新,如下所示:
product | total order | Total sold
milk | 2 | 6
bread | 3 | 7
并且如果说所有milk
产品信息已从表1中删除,它也会触发DELETE;
product | total order | Total sold
bread | 3 | 7
这是我发现的原始问题中的mysql代码;
SELECT a.product, a.sold, b.total_order, b.total_sold
FROM mytable a
JOIN (SELECT product, COUNT(*) AS total_order, SUM(sold) AS total_sold
FROM mytable
GROUP BY product) b ON a.product = b.product
这只是JOINS
到表中的附加列,效率不高,每次加载页面时都需要重新运行。