如果查询有行,如何只运行子查询?

时间:2014-11-11 16:16:51

标签: mysql sql optimization subquery

我在像这样的mysql中运行更新查询。它旨在更新mytable 中记录5的mycount和mysum列,当且仅当 mycount为null时。

如果它不为null,则没有要更新的行,但子查询仍然会运行,这很昂贵。有没有办法创建一个只在有更新内容时才运行子查询的查询?

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;

1 个答案:

答案 0 :(得分:1)

如果有行,此版本应仅运行子查询。但是,它的缺点是每次更新的行都运行两次:

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;

只要子查询不包含mytable,就可以执行此操作。

编辑:

我不确定以下内容是否有效,但它可能在实践中有效:

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;

我只是不认为MySQL保证评估set条款的顺序。但它通常会按照书面形式进行。