表 EventGroup 有欄位 joinCount,需根據 EventGroupMember 滿足條件的記錄數更新。
UPDATE EventGroup g
SET joinCount = (
SELECT b.counts
FROM (
SELECT eventGroupId, SUM(1) AS counts
FROM EventGroupMember
WHERE groupRoleId < 4
AND (memberStatus = 0 OR memberStatus = 3)
GROUP BY eventGroupId
) b
WHERE b.eventGroupId = g.eventGroupId
)
WHERE EXISTS (
SELECT 1
FROM (
SELECT eventGroupId, SUM(1) AS counts
FROM EventGroupMember
WHERE groupRoleId < 4
AND (memberStatus = 0 OR memberStatus = 3)
GROUP BY eventGroupId
) b
WHERE b.eventGroupId = g.eventGroupId
);
WITH (CTE, 8.0+) 或衍生表 JOIN:WITH stats AS (
SELECT eventGroupId, COUNT(*) AS cnt
FROM EventGroupMember
WHERE groupRoleId < 4 AND memberStatus IN (0,3)
GROUP BY eventGroupId
)
UPDATE EventGroup g
JOIN stats s ON g.eventGroupId = s.eventGroupId
SET g.joinCount = s.cnt;
EventGroupMember(eventGroupId, groupRoleId, memberStatus) 建立複合索引加速聚合。