8

I thought this would be simple but I can't get my head around it...

I have one table tbl1 and it has columns id,otherstuff,num.

I have another table tbl2 and it has columns id,info.

What I want to is make the num column of tbl1 equal to the number of rows with the same id in tbl2. Kind of like this:

UPDATE tbl1 SET num =
(SELECT COUNT(*) FROM tbl2 WHERE id=tbl1.id)

Any ideas?

2
  • 2
    Did you give it a try? Looks a lot like this answer. Commented Apr 17, 2013 at 12:18
  • How weird. I didn't think what I wrote was correct SQL. Commented Apr 17, 2013 at 12:21

2 Answers 2

17

If your num column is a valid numeric type your query should work as is:

UPDATE tbl1 SET num = (SELECT COUNT(*) FROM tbl2 WHERE id=tbl1.id)
Sign up to request clarification or add additional context in comments.

Comments

12
UPDATE tbl1, (select id, count(*) as idCount from tbl2 group by id) as t2
SET    tbl1.num = t2.idCount
WHERE  tbl1.id = t2.id;

2 Comments

This was the perfect solution that is extremely fast on large tables. Thank you.
what does this do when there are 0 corresponding columns for a tbl1 row?

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.