此查询适用于更新字段this_count
,其中包含特定用户($ user_id)邀请的人数:
UPDATE table_one SET invitor_count =
(SELECT count(*) FROM table_one
WHERE invitor =
(SELECT invite_name FROM table_one WHERE user_id = $user_id)
)
WHERE user_id = $user_id;
我可以在一个查询中更新所有invitor_counts吗?我怎么能这样做?
表格结构
+---------+------------+------------+-------------+
| user_id | name | invitor | invite_name |
+---------+------------+------------+-------------+
| 215 | Susan B | Alicia18 | Susan |
| 217 | Alicia L | | Alicia18 |
+---------+------------+------------+-------------+
答案 0 :(得分:2)
我认为以下查询对Oracle有帮助,我不确定MySQL是否有NVL或者还有其他类似的功能。
update table_one z
set invitor_count =
nvl((select count(*)
from table_one x
join table_one y on x.invite_name = y.invitor
where x.user_id = z.user_id), 0)
答案 1 :(得分:1)
UPDATE
table_one AS t
JOIN
( SELECT b.user_id, COUNT(*) AS cnt
FROM
table_one a
JOIN
table_one AS b
ON a.invitor = b.invite_name
GROUP BY b.user_id
) AS grp
ON grp.user_id = t.user_id
SET t.invitor_count = grp.cnt