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

匿名 (未验证) 提交于 2019-12-03 01:10:02

问题:

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 {   @Id   @GeneratedValue(strategy = GenerationType.AUTO)   private Long roomId;    @ManyToOne     @JoinColumn(name = "appartment_id")   private Appartment appartment; }  @Entity public class Appartment {    @Id   @GeneratedValue(strategy = GenerationType.AUTO)   private Long appartmentId;    @OneToMany   @JoinColumn(name="appartment_id")   private Set<Room> roomList; }  update Room r1 set r1.available = :availability where r1.roomId in ( select r2.roomId from Room r2 JOIN r2.appartment a1 WHERE a1.appartmentId = :appartmentId ) 

I get this error

java.sql.SQLException: Table 'room' is specified twice, both as a target for 'UPDATE' and as a separate source for data

回答1:

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  


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!