Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Update a column with count of the values from another column

I am creating a MySQL table with the following query.

CREATE TABLE log_table (id INTEGER, street TEXT, status INTEGER)

and filling it with the following query:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

INSERT INTO log_table (`id`, `street`, `status`) VALUES
  ('1', 'main_street', '0'),
  ('2', '1st_street', '0'),
  ('3', '1st_street', '0'),
  ('4', 'main_street', '0'),
  ('5', '2nd_street', '0'),
  ('6', '1st_street', '0'),
  ('7', 'main_street', '0'),
  ('8', '2nd_street', '0'); 

I am trying to update the status column with the count of the street column.
For example for the first row status column should be 3 because main_street appears 3 times in street column.

I have tried the following query but it doesn’t work.

UPDATE log_table l1 SET status = 
(SELECT COUNT(*) FROM log_table l2 WHERE l2.street = l1.street);

It gives an error that says "You can’t specify target table ‘l1’ for update in FROM clause". What could be the issue?

>Solution :

You can use a join:

  UPDATE log_table l1 
     join (SELECT COUNT(*) as n, street  FROM log_table l2 group by l2.street) as l3 on l1.street=l3.street 
  SET status = l3.n

SQLFiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading