我有一个表dutyrecord,存储多个用户工作时间(小计) 和一个UserID(志愿者ID)。通过以下选择语句,我将为每个UserID设置总小时数:
SELECT
dutyrecord.VolunteerID,
SEC_TO_TIME( SUM( TIME_TO_SEC( SubTotal ) ) ) AS total
FROM
volunteerinfo
INNER JOIN
dutyrecord ON
( volunteerinfo.VolunteerID = dutyrecord.VolunteerID )
GROUP BY
dutyrecord.VolunteerID
我可以将更新语句与select结合使用来更新每个用户的总小时数吗?我尝试过类似的东西和其他一些没有运气的方法:
UPDATE volunteerinfo
SET
TotalHours =
(
SELECT dutyrecord.VolunteerID ,
SEC_TO_TIME( SUM( TIME_TO_SEC( SubTotal ) ) ) AS total
FROM
volunteerinfo
INNER JOIN
dutyrecord ON ( volunteerinfo.VolunteerID = dutyrecord.VolunteerID )
GROUP BY
dutyrecord.VolunteerID
)
WHERE
volunteerinfo.VolunteerID = dutyrecord.VolunteerID`
任何人都可以帮我解决这个问题吗?
更新
对不起,尝试了一些其他例子,我找到了答案,并提出了一个更清晰的问题。
清除我的问题:我可以将这个过程合并为一个,因为我想让这个过程语言独立吗? (我只是在不同的执行中携带1个SQL语句。)
首先,我选择一张桌子给我每个人的工作时间总和
SELECT VolunteerID,SEC_TO_TIME(SUM(TIME_TO_SEC(SubTotal)))AS总计 来自dutyrecord GROUP BY VolunteerID
e.g。 ID:10001,1:00:02 ID:2001,10:00:34 ....
之后,我想根据ID
将结果(总计)更新到另一个表中更新Volunteerinfo 设置Volunteerinfo.totalhours = dutyrecord.total 其中Volunteerinfo.VolunteerID = dutyrecord.VolunteerID
答案 0 :(得分:0)
问题是您只更新了一个字段TotalHours
,但您的子查询正在选择2个字段(dutyRecord.VolunteerID
和total
)。只需从子查询中删除dutyrecord.VolunteerID
即可。新查询应如下所示:
编辑:您还需要在dutyrecord
语句中加入UPDATE
,因为您要在WHERE
条件中引用它。
UPDATE volunteerinfo, dutyrecord
SET
volunteerinfo.TotalHours =
(
SELECT
SEC_TO_TIME( SUM( TIME_TO_SEC( SubTotal ) ) ) AS total
FROM
volunteerinfo
INNER JOIN
dutyrecord ON ( volunteerinfo.VolunteerID = dutyrecord.VolunteerID )
GROUP BY
dutyrecord.VolunteerID
)
WHERE
volunteerinfo.VolunteerID = dutyrecord.VolunteerID
答案 1 :(得分:0)
我对此的回答是首先将两个表连接在一起,然后update和select语句将在一行中工作。如果内部联接或其他方式会提高此查询的性能,也请评论我。
update volunteerinfo I
join
(SELECT VolunteerID, SEC_TO_TIME( SUM( TIME_TO_SEC( SubTotal ) ) ) AS total
FROM dutyrecord
GROUP BY VolunteerID) R on R.volunteerid = I.volunteerid
set I.totalhours = R.total