我有一个令人烦恼的问题,我正在尝试使用更新查询...以下语句应该将channels.media_view_count更新为子查询的结果(适用于所有通道)。
UPDATE channels c
SET c.media_view_count = (
SELECT SUM(t.view_count)
FROM (
SELECT DISTINCT m.viewkey, m.view_count
FROM media m
INNER JOIN participants p ON m.id = p.medium_id
WHERE p.user_id = c.id AND m.is_viewable = 1
AND (p.pending = 0)
) AS t
);
子查询可以独立工作(当指定c.id的实际id时,如47778或其他),但当我执行此语句时,我得到:
ERROR 1054 (42S22): Unknown column 'c.id' in 'where clause'
我以为我能够从子查询中访问channels表(别名为c)?我错过了什么或者我在这里完全错了吗?
赞赏任何和所有帮助:)
谢谢,
答案 0 :(得分:6)
UPDATE channels c, (
SELECT t.user_id, SUM(t.view_count) cnt
FROM (
SELECT DISTINCT p.user_id, m.viewkey, m.view_count
FROM media m
INNER JOIN participants p ON m.id = p.medium_id
WHERE m.is_viewable = 1
AND (p.pending = 0)
) AS t GROUP BY t.user_id ) temp
SET c.media_view_count = temp.cnt
WHERE c.id = temp.user_id
尝试这样......虽然没有测试:) .. 从概念上讲,它应该起作用