Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Count records from one table and then update another

Tags:

sql

mysql

Got 2 tables / entities, very straightforward scenario.

Table poets - Columns: id, poet, nation

Table nations - Columns: id, nation, count

Basically, nations to poets has a mapping of one to many, naturally. For example, there are 1000 poets from 60 nations. Each poet in poets is assigned to a nation by the nation field which contains the id of one of the nations in nations.

The count field of nations contains the number of poets in poets from this nation.

My question is how to use just one SQL query to count the number of poets by nation in poets and then update the corresponding count of that nation?

I tried:

UPDATE poets, nations SET nations.count = COUNT(poets.id) GROUP BY poets.nation HAVING poets.nation = nations.id

But it gives #1064 error. Also tried to combine WHERE clause somewhere but it still refuses to work.

Any idea?

like image 727
datasn.io Avatar asked Aug 01 '09 08:08

datasn.io


2 Answers

Use a subquery:

UPDATE nations 
   SET count = (
       SELECT COUNT(id) 
         FROM poets 
        WHERE poets.nation = nations.id 
        GROUP BY id
       );
like image 146
Zed Avatar answered Nov 09 '22 17:11

Zed


You just do not need GROUP BY, cf.:

UPDATE nations SET count = (
  SELECT COUNT(id) FROM poets 
    WHERE poets.nation = nations.id);

Or rather, with GROUP BY, the subquery will return NULL for nations that have no poets. Without GROUP BY, the subquery will return 0 in this case.

like image 27
mikhailian Avatar answered Nov 09 '22 19:11

mikhailian