19

This type of thing has been asked a few times before, but is not quite what I am looking for. I need to SET two rows equal to different parts of a subquery.

I am currently using:

UPDATE records
SET leads=(SELECT COUNT(*) FROM leads_table WHERE leads_table.blah=records.blah),
earnings=(SELECT SUM(amount) FROM leads_table WHERE leads_table.blah=records.blah)

The WHERE statements were obviously simplified...but basically its the same subquery but I don't think I should be running it twice?

I want to do something like...

UPDATE records
SET (leads,earnings)=(SELECT COUNT(*),SUM(amount) FROM leads_table WHERE leads_table.blah=records.blah)

1 Answer 1

48

You can simply join the table in a subquery that do some calculations,

UPDATE  records a
        INNER JOIN
        (
            SELECT  blah, 
                    COUNT(*) totalCount,
                    SUM(amount) totalSum
            FROM    leads_table
            GROUP   BY blah
        ) b ON  b.blah = a.blah
SET     a.leads = b.totalCount,
        a.earnings = b.totalSum
Sign up to request clarification or add additional context in comments.

4 Comments

Nice indeed, elegant and fast.
Is it fast? Would it not calc count/sum for every blah even if you are only selecting one?
needs a comma after the first set
I think it works well but beware if all rows in leads_table referring to a specific row of records are removed, I don't think it will update the field in records back to zero properly, so would need to zero all first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.