mysql update 所有字段的值,MySQL UPDATE WHERE IN分别为每个列出的值?

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.

解决方案

You can do this with two 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);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值