简体   繁体   English

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

[英]How to only run subquery if query has rows?

I'm running an update query in mysql like this one. 我正在像这样在mysql中运行更新查询。 It is designed to update the mycount and mysum columns of record 5 in mytable if and only if mycount is null. 当且仅当 mycount为null时,它才设计为更新mytable中记录5的mycount和mysum列。

If it's not null, there are no rows to update, but the subquery still gets run, which is expensive. 如果不为null,则没有要更新的行,但是子查询仍然可以运行,这很昂贵。 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 . 只要子查询不包含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. 我只是认为MySQL不保证set子句的求值顺序。 But it would normally do them as written. 但这通常会按书面要求进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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