gpt4 book ai didi

mysql - 从子查询更新多列

转载 作者:IT老高 更新时间:2023-10-29 00:14:02 26 4
gpt4 key购买 nike

这种类型的问题之前已经问过几次,但不是我要找的。我需要 SET 两行等于子查询的不同部分。

我目前正在使用:

UPDATE records
SET leads=(SELECT COUNT(*) FROM leads_table WHERE leads_table.blah=records.blah),
earnings=(SELECT SUM(amount) FROM leads_table WHERE leads_table.blah=records.blah)

WHERE 语句显然得到了简化...但基本上它是相同的子查询,但我认为我不应该运行它两次?

我想做类似...

UPDATE records
SET (leads,earnings)=(SELECT COUNT(*),SUM(amount) FROM leads_table WHERE leads_table.blah=records.blah)

最佳答案

您可以简单地在执行一些计算的子查询中加入表,

UPDATE  records a
INNER JOIN
(
SELECT blah,
COUNT(*) totalCount,
SUM(amount) totalSum
FROM leads_table
GROUP BY blah
) b ON b.blah = a.blah
SET a.leads = b.totalCount
a.earnings = b.totalSum

关于mysql - 从子查询更新多列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16473402/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com