简体   繁体   English

MySQL更新与子查询

[英]MySQL Update with Subquery

I've got an annoying issue with an update query I'm trying to get working... The following statement SHOULD update channels.media_view_count to the result of the subquery (for all channels). 我在尝试使用更新查询时遇到了一个令人烦恼的问题...以下语句应将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
  );

The subquery works fine independently (when specifying an actual id for c.id, like 47778 or whatever), but when I execute this statement, I get: 子查询可以独立正常工作(当为c.id指定实际ID时,例如47778或其他),但是当我执行此语句时,我得到:

ERROR 1054 (42S22): Unknown column 'c.id' in 'where clause'

I thought I would be able to access the channels table (aliased as c) from within the subquery? 我以为我可以从子查询中访问通道表(别名为c)? Am I missing something or am I totally wrong here? 我在想什么吗?还是我完全错了?

Any and all help is appreciated :) 任何和所有帮助表示赞赏:)

Thanks, 谢谢,

  • Jeff 杰夫
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

Try like this... Did not test it though :) .. 像这样尝试...虽然没有测试:) ..
Conceptually, it should work 从概念上讲,它应该起作用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM