How to UPDATE table with SUM() and COUNT() in same table to different columns

孤者浪人 提交于 2021-02-19 07:53:18

问题


I currently dont do this for my webpage for displaying data from the table, and it is now taking longer to load the page as more and more data enters the database making the query time consuming. In my head, I am looking to update a table as follows so that I am just querying the table and not running additional arrhythmic on the contents via SELECT functions. I was planning to run something like this in a while loop to cycle all iterations of the user variable.

UPDATE table
SET total = SUM(sales)
SET orders = COUNT(order)
GROUP by user
WHERE user=$id

回答1:


try it use update value from left join (sum + count) table

update T T1
  left join (
    select `user`,sum(`sales`) newtotal,count(`order`) neworders
    from T
    group by `user`
  ) T2 on T1.`user` = T2.`user`
set T1.total = T2.newtotal,T1.orders = T2.neworders

Test DDL:

CREATE TABLE T
    (`user` varchar(4), `sales` int, `order` varchar(7), `total` int, `orders` int)
;

INSERT INTO T
    (`user`, `sales`, `order`, `total`, `orders`)
VALUES
    ('xx01', 100, 'order01', 0, 0),
    ('xx02', 200, 'order02', 0, 0),
    ('xx02', 400, 'order03', 0, 0),
    ('xx03', 300, 'order04', 0, 0),
    ('xx03', 500, 'order05', 0, 0)
;

Result:

| user | sales |   order | total | orders |
|------|-------|---------|-------|--------|
| xx01 |   100 | order01 |   100 |      1 |
| xx02 |   200 | order02 |   600 |      2 |
| xx02 |   400 | order03 |   600 |      2 |
| xx03 |   300 | order04 |   800 |      2 |
| xx03 |   500 | order05 |   800 |      2 |

TEST DEMO LINK




回答2:


You can express this as a single update query using join:

UPDATE t JOIN
       (SELECT user, SUM(sales) as toal, COUNT(order) as orders
        FROM t
        GROUP BY user
       ) tt
       ON t.user = tt.user
    SET t.total = tt.total,
        t.orders = tt.orders;

That said, this approach doesn't really make sense. First, I would question whether or not you really need this approach. Your SQL is pretty bad, so I'm guessing you haven't tried to optimize the actual query you are using. If that is of interest, ask another question, with sample data, desired results, and the query you are using.

The normal approach to improving performance in this situation is to have a separate table with one row per user and a column for each summarized statistic. You would maintain this table with triggers -- for updates, deletes, and inserts -- so the data is always up-to-date.



来源:https://stackoverflow.com/questions/51296435/how-to-update-table-with-sum-and-count-in-same-table-to-different-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!