所以我有几张桌子:
___ TABLE A (users info) ___
team_id | user_id | points | rewards
___ TABLE B (points for every event)___
team_id | user_id | points | rewards | event_type
___ Table C (users) ___
user_id | name | etc..
在表A中,我有基于团队的所有用户的摘要信息。在表B中,我有每个事件的原子信息(类似于历史)。我想仅使用user_id通过表B中的某些相同字段更新表A(点和奖励)中的信息。我的问题是我无法理解如何在一个查询中执行此操作。
例如,我可以进行类似
的查询WITH storage as (
SELECT
sum(points) as points,
sum(rewards) as rewards,
team_id FROM B
WHERE user_id = 1 AND team_id = 1
)
UPDATE A
SET
points = (
SELECT points FROM storage
),
rewards = (
SELECT rewards FROM storage)
WHERE user_id = 1 and team_id = 1 ;
但我想在没有team_id的情况下运行此操作。例如,我运行像
这样的sqlWITH storage as (
SELECT
sum(points) as points,
sum(rewards) as rewards,
team_id FROM B
WHERE user_id = 1 GROUP BY team_id
)
在此更新之后,基于team_id为表B中的每一行指出并奖励。 是否可以在后端进行无循环查询? 的更新: 它适用于SQLite数据库 更新2 您可以找到回复enter link description here
答案 0 :(得分:0)
喜欢这个吗?
update A set A.points = B.sumpoints, A.reward = B.sumreward
from A,
(select userid, teamid, sum(points) sumpoints, sum(reward) sumreward
from B group by userid, teamid) B
where A.userid = B.userid and A.teamid = B.teamid
答案 1 :(得分:0)
所以最后我找到了SQLite的解决方案。它非常接近我的第一个查询。
WITH storage as (
SELECT
sum(points) as points,
sum(rewards) as rewards,
team_id FROM B
WHERE team_id IS NOT NULL AND user_id = 1
GROUP BY team_id
)
UPDATE A
SET
points = (
SELECT points FROM storage WHERE storage.team_id = A.team_id
),
rewards = (
SELECT rewards FROM storage WHERE storage.team_id = A.team_id
)
WHERE user_id = 1;
还可以删除未使用的数据以将where语句添加到WITH存储块(通过user_id添加过滤器)
(sales, sales.map