1

以下查询像 7 次一样更新同一个表。我希望您能帮助我通过将它放入一个查询中来优化它,以便它只通过表一次而不是 7 次。这确实会降低性能大数据集..

谢谢。

PS我不知道它是否仍然有效,但每个查询字符串都取决于它之前的查询来准确计算。所以如果我们需要将它们分开以保持准确,那么我可以使用一些帮助来优化每个字符串(查询)单独。

以下 SQL 查询是在 Delphi 2009 中进行的,因此格式可能会有所不同,但您仍然应该能够很容易地阅读查询..

Str1 :=
'update user set amount = ' +
  '(select round(sum(bill.amount),2) from bill where ' +
  'bill.user = user.code); ' +
'update user set pay = ' +
  '(select round(sum(bill.pay),2) from bill where ' +
  'bill.user = user.code); ' +
'update user set balance = round(amount + pay,2);';

//execute query

 Str1 :=
'update user set group_amt = ' +
  '(select sum(bill.amount) from bill where ' +
  'bill.client = user.client); ' +
'update user set group_pay = ' +
  '(select sum(bill.pay) from bill where ' +
  'bill.client = user.client); ' +
'update user set group_bal = round(group_amt + group_pay,2);';

 //execute query

Str1 :=
'update user set bal_flag = true ' +
'where abs(balance) > 0.001 and bal_flag = false;';
4

1 回答 1

3

我怀疑您可以将 6 个更新合并为 2 个更新...

UPDATE
  user
SET
  amount   = bill.amount,
  pay      = bill.pay,
  balance  = bill.pay + bill.amount
FROM
(
  SELECT
    user,
    round(sum(bill.amount),2)   AS amount,
    round(sum(bill.pay)   ,2)   AS pay
  FROM
    bill
  GROUP BY
    user
)
  AS bill
WHERE
  bill.user = user.code

而且几乎一样...

UPDATE
  user
SET
  group_amt = bill.amount,
  group_pay = bill.pay,
  group_bal = bill.pay + bill.amount
FROM
(
  SELECT
    client,
    round(sum(bill.amount),2)   AS amount,
    round(sum(bill.pay)   ,2)   AS pay
  FROM
    bill
  GROUP BY
    client
)
  AS bill
WHERE
  bill.client = user.client
于 2012-07-02T15:54:58.860 回答