views:

259

answers:

2

Hi,

I've got the following type of SQL:

UPDATE photo AS f 
  LEFT JOIN car AS c 
         ON f.car_id=c.car_id 
  SET f.photo_status=1
    , c.photo_count=c.photo_count+1 
  WHERE f.photo_id IN ($ids)

Basically, two tables (car & photo) are related. The list in $ids contains unique photo ids, such as (34, 87, 98, 12). With the query, I'm setting the status of each photo in that list to "1" in the photo table and simultaneously incrementing the photo count in the car table for the car at hand.

It works but there's one snag: Because the list can contain multiple photo ids that relate to the same car, the photo count only ever gets incremented once. If the list had 10 photos associated with the same car, photo_count would become 1 .... whereas I'd like to increment it to 10.

Is there a way to make the incrementation occur for each photo individually through the join, as opposed to MySQL overthinking it for me?

I hope the above makes sense. Thanks.

+1  A: 

What I think you should do:

update the tables in two steps. First set the status to 1 in photo table, then update the count (by using group by and count(...) ) to car table.

EDIT Retracted the 'naive approach' , won't work as the OP correctly states!

lexu
You've misunderstood the question. $ids contain multiple photo ids that relate to different cars in different quantities. Adding them to photo_count will not work at all. Secondly, the query can be broken into two only by looping the second query, which means that if there are 40 photos, there will be 1 + 40 queries.
Tom
I see what you mean by "You've misunderstood the question." and I agree .. I didn't catch that the count will be different on a car by car basis! Never the less, I think you should consider doing it in two steps: updating (recalculate) the number of pictures per car. I should have written 'update' not add, so I corrected that.
lexu
No worries, thanks for contributing.
Tom
+1  A: 

you can do this with 2 queries :

update car set photo_count = photo_count + (select count(*) from photos where photo.car_id = car.car_id AND photo_status = 0 AND photo_id IN ($ids));

update photo set photo_status = 1 WHERE photo_id IN ($ids);

oedo
This looks promising thanks. Will test it....
Tom
Thank you, this works and does the job, probably the simplest way.
Tom