3

Assume I have the following database table structure:

A >- B -< C >- D

where >- is a many-to-one relation and -< one-to-many.

Now I would like to delete all A entries which correspond to an D with a given name.

One might say that

DELETE FROM A JOIN B ON <condition> JOIN C ON <condition> JOIN D ON <condition> WHERE D.name=?

would be a solution. Sadly, it appears that you cannot have a JOIN clause in a DELETE query.

Another approach was to have a sub-query, like this:

DELETE FROM A AS elem WHERE elem.id IN ( SELECT id FROM A JOIN B ON <condition> JOIN C ON <condition> JOIN D ON <condition> WHERE D.name=?);

While this might work in Oracle, MySQL will not let me do this(I cannot make a select on the table I'm about to delete from).

So how should I accomplish this?

To be more precise, I am using Hibernate and it's HQL to create this query. So a JPA/Hibernate solution would be preferred.

Of course, simple SQL will also do(I will try to translate it into HQL).

4

1 回答 1

3

是的,您可以通过加入删除。MySQL 文档中描述了语法:DELETE

DELETE A                     -- you only need to add `A` here, so it knows
                             -- which table to delete from
FROM A 
  JOIN B ON <condition> 
  JOIN C ON <condition> 
  JOIN D ON <condition> 
WHERE D.name = ? ;

子查询方法也可以。如果用于执行的条件A join BON A.xid = B.xid,那么您可以使用:

DELETE FROM A 
WHERE A.xid IN 
      ( SELECT B.xid 
        FROM B 
          JOIN C ON <condition> 
          JOIN D ON <condition> 
        WHERE D.name = ?
      ) ;

但我不会用这个。子查询IN有时表现不佳。


另一种方法是相关EXISTS子查询:

DELETE FROM A 
WHERE EXISTS 
      ( SELECT 1  
        FROM B 
          JOIN C ON <condition> 
          JOIN D ON <condition> 
        WHERE D.name = ?
          AND A.xid = B.xid       -- the condition for "A JOIN B"
      ) ;
于 2013-09-06T08:22:59.193 回答