更新where count with count mysql

时间:2012-12-18 03:25:42

标签: mysql sql join sql-update

我有一个名为'people'的表,人们有一个名为'appearances'的关联表。我想用MySQL中的左连接选择'appearance_count'来更新people表。我只是在语法方面遇到了一些麻烦。我将更新语句放在以下查询中的哪个位置。我尝试了类似于此的更新,但我不断收到错误'无法更新与所选表相同的表'(或者那种效果)。这是我的查询原始选择形式:

 SELECT        people.*, 
 COUNT(appearances.id) as app_count,
 FROM          `people`
 INNER JOIN    `appearances`
 ON            `appearances`.`person_id` = `people`.`id`
 GROUP BY      `people`.`id`
 HAVING        app_count > 0;

我如何使用“app_count”并将people.appearance_count设置为该值?

1 个答案:

答案 0 :(得分:4)

我认为HAVING不是必需的,因为它会过滤COUNT大于零的记录,并使用PEOPLE将其加入表LEFT JOIn

UPDATE  people a
        LEFT JOIN
        (
            SELECT b.id, COUNT(c.person_ID) totalCOunt
            FROM    people b
                    INNER JOIN    appearances c
                        ON c.person_id = b.id
            GROUP BY b.id
        ) d ON a.ID = d.ID
SET     a.appearance_count = d.totalCount