我有以下两个表格:
users:
id 7dexpn
=========== ==========
1 0
2 0
3 0
user_pages:
id user_id 7dexpf
========== =========== ==========
99 1 0
98 2 1
97 3 1
96 3 1
95 3 1
94 2 0
我正在尝试将{user_pages聚合的(7dexpf)标记}插入到用户表(7dexpn)中, user_pages(user_id)与用户表(id) <匹配/ p>
预期结果应为:
users:
id 7dexpn
=========== ==========
1 0
2 1
3 3
答案 0 :(得分:1)
尝试使用以下查询
UPDATE users u,
(
SELECT
user_id,
SUM(7dexpf) AS 7dexpf
FROM
user_pages up
GROUP BY
user_id
) upp
SET 7dexpn = upp.7dexpf
WHERE
u.id = upp.user_id
答案 1 :(得分:1)
您想要汇总user_pages
中的值,然后分配它们。我愿意:
update users u join
(select user_id, count(*) as cnt
from user_pages
where `7dexpf` = 1
group by user_id
) uu
on uu.user_id = u.id
set u.`7dexpn` = uu.cnt;
答案 2 :(得分:0)
您可以使用此方式加入聚合值
update users u
join ( select user_id, sum( case when `7dexpf` =1 1 else 0 end ) tot_7dexpf
from user_pages
group by user_id) t1 on t1.user_id = u.id
set u.`7dexpf` = t1tot_7dexpf
我建议使用避免列名以数字开头,或者在这种情况下使用反引号,例如:
`7dexpf`
答案 3 :(得分:0)
我成功地通过这样的方式为社区欢呼
$query=" UPDATE users c
INNER JOIN (
SELECT user_id, SUM(7dexpf) as total
FROM user_pages
GROUP BY user_id
) x ON c.id = x.user_id
SET c.7dexpn = x.total
";