0

I have table like this:

id business_id path     photo
 1          11 1.jpg        0
 2          11 2.jpg        0
 3          15 1.jpg        0
 4          15 3.jpg        0
 5          15 4.jpg        0
 6          21 scan1.jpg    0
 7          21 scan2.jpg    0
 8          22 1.jpg        1

....

I want to update table so that for each business lets say in above scenario for business 11. one of the path should have photo set to 1.

If photo is already set to 1 (like for business_id = 22) above it should not change that.

I think below query will work for 1 business_id at a time:

Update business 
set photo = 1 
where id  = 11 limit 1

But my question is how can I run this in a batch? So I can update all at once.

0

2 Answers 2

1

You can update your table by using below query,It will get the maximum for each business_id which has all photos set to 0 and using join you sub select will update a single record per business_id to photo = 1

update business b
join (select max(id) id, business_id
from business 
group by business_id
having sum(photo = 0) = count(*)) t
on(b.id = t.id)
set b.photo = 1

DEMO

Sign up to request clarification or add additional context in comments.

5 Comments

This would be correct if count() were changed to 0, since as I understand question he wants 1 photo=1 for each distinct id.
@JoeMurray - Can you please tell which part of query to change?
@JoeMurray see the demo part of answer ,also sum(photo = 0) = count(*) will will ensure the resultant business_ids have all photos set to 0 and updating part will update only 1 row per business_id with photo = 1
@MKhalidJunaid - If i am correct if i set min instead of max it will mark first photo rather than last right?
@NoviceMe yes you are correct you can set the minimum one by using min
1

You could try this query:

UPDATE business SET photo = 1 WHERE id IN
   (SELECT MIN(id) , MAX(photo) FROM business
    GROUP BY business_id HAVING max(photo) = 0)

Additional info: The next query gives you a list of rows where business doesn't have any photo. This query was the initial point for my answer.

SELECT business_id , MAX(photo) FROM business
GROUP BY business_id HAVING max(photo) = 0

2 Comments

This would result in setting a second photo to 1 for an id that already had a 1.
It didn't should. I am skipping the rows where business.photo had already a 1 with this clause HAVING max(photo) = 0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.