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 ....)

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)

Your Answer

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

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