Reputation: 4907
I have a table called 'people' and people has an associated table named 'appearances'. I'd like to update the people table with the 'appearance_count' selected with a left join in MySQL. I'm just having some trouble with the syntax. Where would I put my update statement in the following query. I tried an update similar to this but I kept getting an error 'cannot update same table as selected table' (or something to that effect). Here is my query in its raw select form:
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;
How would I take "app_count" and set people.appearance_count to be that value?
Upvotes: 1
Views: 1415
Reputation: 263783
I think HAVING
is not necessary because it will filter records that have a COUNT
of greater than zero and you're joining it with table PEOPLE
using 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
Upvotes: 4