Take the 2-minute tour ×
Database Administrators Stack Exchange is a question and answer site for database professionals who wish to improve their database skills and learn from others in the community. It's 100% free, no registration required.
update activitybooking set `submitted`='1' where id='958'
    and (select SUM(pool1_count) from (select pool1_count from `activitybooking` where `abt`='12' and
                            (id='958' or `submitted`='1' or `submitted`='3' or `submitted`='8')) as temp_pool1_count) < 10
    and (select SUM(pool2_count) from (select pool2_count from `activitybooking` where `abt`='12' and
                            (id='958' or `submitted`='1' or `submitted`='3' or `submitted`='8')) as temp_pool2_count) < 5
    and (select SUM(pool3_count) from (select pool3_count from `activitybooking` where `abt`='12' and
                            (id='958' or `submitted`='1' or `submitted`='3' or `submitted`='8')) as temp_pool3_count) < 20

The statement above has three identical subqueries and seems to execute them independently. How can I best rewrite the update to perform the subquery only once?

(The idea of this query is to only perform the update if doing so would not cause the sum of pool1_count to exceed the maximum allowed pool1_count and the same for pool2, pool3 ....)

share|improve this question

1 Answer 1

MySQL lacks common table expressions but you can achieve the same goal here with the multiple-table update syntax:

update activitybooking 
       cross join ( select sum(pool1_count) p1, sum(pool2_count) p2, sum(pool3_count) p3
                    from `activitybooking` 
                    where `abt`='12' and (id='958' or `submitted`='1' or `submitted`='3' or `submitted`='8') ) z
set `submitted`='1'
where id='958' and p1

(SQLFiddle here)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.