Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL update value from the same table with count

What I want to do is to set every patient its unique patient code which starts with 1 and it's not based on row id. Id only specifies order. Something like this:

patient_id  patient_code
    2           1
    3           2
    4           3

This is my query:

UPDATE patients p1
SET p1.patient_code = (
    SELECT COUNT( * ) 
    FROM patients p2
    WHERE p2.patient_id <= p1.patient_id 
)

But it is throwing error:

#1093 - You can't specify target table 'p1' for update in FROM clause

I found this thread: Mysql error 1093 - Can't specify target table for update in FROM clause.
But I don't know how to apply approved answer this to work with subquery WHERE which is necessary for COUNT.

like image 855
Jan.J Avatar asked Jan 03 '13 12:01

Jan.J


People also ask

How do I UPDATE multiple values in MySQL?

MySQL UPDATE multiple columnsMySQL UPDATE command can be used to update multiple columns by specifying a comma separated list of column_name = new_value. Where column_name is the name of the column to be updated and new_value is the new value with which the column will be updated.

How UPDATE multiple columns with same value in SQL?

To update multiple columns use the SET clause to specify additional columns. Just like with the single columns you specify a column and its new value, then another set of column and values. In this case each column is separated with a column.


1 Answers

UPDATE
    patients AS p
  JOIN
    ( SELECT 
          p1.patient_id
        , COUNT(*) AS cnt 
      FROM 
          patients AS p1
        JOIN 
          patients AS p2
            ON p2.patient_id <= p1.patient_id 
      GROUP BY 
          p1.patient_id
    ) AS g
    ON g.patient_id = p.patient_id
SET 
    p.patient_code = g.cnt ;
like image 138
ypercubeᵀᴹ Avatar answered Sep 27 '22 22:09

ypercubeᵀᴹ