Table is specified twice, both as a target for 'UPDATE' and as a separate source for data

前端 未结 1 1362
暖寄归人
暖寄归人 2021-01-14 19:56

I use spring-jpa with hibernate implementation. I use mariadb and I try to do an update subquery

My object structure

@Entity
public class Room {
  @         


        
1条回答
  •  离开以前
    2021-01-14 20:25

    This is a restriction in MySQL:-

    http://dev.mysql.com/doc/refman/5.7/en/update.html

    You cannot update a table and select from the same table in a subquery.

    There is a fudge you can do sometimes do to hide the sub query in a a further level of sub query that might work. Something like this (not tested):-

    UPDATE Room r1
    SET r1.available = :availability
    WHERE r1.roomId IN
        SELECT roomId
        FROM
        ( 
            SELECT r2.roomId 
            FROM Room r2 
            JOIN r2.appartment a1 
            WHERE a1.appartmentId = :appartmentId 
        )
    

    Note that your query possibly has an error. In the sub query you are joining the table Room aliased as r2 to a table called appartment on a database called r2. Also your sub query does a JOIN without a join condition.

    However you can quite possibly just do the join in the UPDATE statement without the need for a sub query:-

    UPDATE Room 
    INNER JOIN r2.appartment a1
    ON Room.roomId = a1.roomId
    SET r1.available = :availability
    WHERE a1.appartmentId = :appartmentId 
    

    0 讨论(0)
提交回复
热议问题