简体   繁体   中英

Self-referencing MySQL table in UPDATE-query

I have the following scenario:

3 tables are involved, 'patient', 'users' and 'center'. They have the following attributes and relationships:

'patient':

  • pid = primary key
  • doc = foreign key to 'uid' of 'users'
  • localid = set to '-1' by default

'users':

  • uid = primary key
  • cid = foreign key to 'cid' of 'center'

'center':

  • cid = primary key

Patients aren't directly assigned to a center. Instead, they are assigned to a specific user, who in turn is assigned to one center.

The 'localid' of the patient is currently set to '-1' for all patients. I'm trying to come up with a SQL query which increments the 'localid' for all patients, but only within the center they are indirectly associated with through the user.

In essence, I want all patients to have a unique ID within their center, but it should start at 0 for each center.

This is the query I have tried, which I think is close to what I need:

UPDATE patient p1
SET p1.localid=(SELECT (max(p2.localid) +1)
                FROM patient p2
                WHERE (SELECT u1.cid
                       FROM users u1
                       WHERE u1.uid=p1.doc)=(SELECT u2.cid
                                             FROM users u2
                                             WHERE u2.uid=p2.doc));

This results in the sql error "You can't specify target table 'p1' for update in FROM clause" because 'p1' is referencing itself in the WHERE-clause.

I can easily solve this problem by using multiple SQL queries and a loop in PHP, but I was wondering if it was possible to solve this with just plain SQL?

Instead of using subqueries, you can JOIN the table to itself using the criteria from your subquery and give it an alias. That should allow you to update the same table you're querying.

Something like...

UPDATE patient p1
SET p1.localid = p2.newlocalid
INNER JOIN (
    SELECT pid, MAX(localid) + 1 AS newlocalid
    FROM patient p2
    WHERE...
) p2 ON p1.pid = p2.pid

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM