简体   繁体   中英

How to only run subquery if query has rows?

I'm running an update query in mysql like this one. It is designed to update the mycount and mysum columns of record 5 in mytable if and only if mycount is null.

If it's not null, there are no rows to update, but the subquery still gets run, which is expensive. Is there any way to create a query that will only run the subquery if there is anything to update?

UPDATE mytable
CROSS JOIN (
  SELECT COUNT(*) thiscount, SUM(mycolumn) thissum
  FROM(
    SELECT mycount, mysum
    FROM <some complicated query>
  )t
)t2
SET mycount=thiscount,
    mysum=thissum
WHERE id=5;
  AND mycount IS NULL;

This version should only run the subquery if there are rows. But, it has the downside of running it twice for each row being updated:

UPDATE mytable
    SET mycount = (SELECT COUNT(*) as thiscount
                   FROM (SELECT mycount, mysum
                         FROM <some complicated query>
                        ) t
                  ),
        mysum = (SELECT SUM(mycolumn) as thissum
                 FROM (SELECT mycount, mysum
                       FROM <some complicated query>
                      ) t
                 )
    WHERE id = 5 AND mycount IS NULL;

You can do this so long as the subqueries do not contain mytable .

EDIT:

I'm not sure that the following is guaranteed to work, but it might work in practice:

UPDATE mytable
    SET mycount = (SELECT (CASE WHEN @x := SUM(mycolumn) THEN COUNT(*)
                                ELSE COUNT(*)
                           END) as thiscount
                   FROM (SELECT mycount, mysum
                         FROM <some complicated query>
                        ) t
                  ),
        mysum = @x
    WHERE id = 5 AND mycount IS NULL;

I just don't think that MySQL guarantees the order of evaluation of set clauses. But it would normally do them as written.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM