从子查询中删除

时间:2013-08-28 13:30:35

标签: mysql sql hibernate jpa

我在我的应用程序中使用Hibernate。目前我正在尝试执行以下查询:

DELETE FROM ActiveTimes a WHERE
a.begin>=:from AND a.begin<=:to
AND a.end>=:from AND a.end<=:to
    AND a in( 
         SELECT al FROM ActiveTimes al 
             JOIN al.source.stage st
         JOIN st.level.dataSource ds
     WHERE ds=:dataSource)

但我收到错误:Column 'id' in field list is ambiguous。 这感觉很正常,因为创建的SQL查询如下所示:

delete 
from
    active_times 
where
    begin>=? 
    and begin<=? 
    and end>=? 
    and end<=? 
    and (
        id in (
            select
                id 
            from
                active_times activeti1_ 
            inner join
                sources sourc2_ 
                    on activeti1_.source=sourc2_.id 
            inner join
                stage stage3_ 
                    on sourc2_.id=stage3_.source 
            inner join
                levels levels4_ 
                    on stage3_.level=levels4_.id 
            inner join
                datasources datasource5_ 
                    on levels4_.data_source=datasource5_.id 
            where
                id=?
        )
    )

如果我将查询更改为:

DELETE FROM ActiveTimes a WHERE
a.begin>=:from AND a.begin<=:to
AND a.end>=:from AND a.end<=:to
    AND a.id in( 
         SELECT al.id FROM ActiveTimes al 
             JOIN al.source.stage st
         JOIN st.level.dataSource ds
     WHERE ds.id=:dataSource)

我收到另一个错误:You can't specify target table 'active_times' for update in FROM clause

我没有尝试过JPQL(或HQL),所以我不明白为什么查询在第一个例子中看起来像那样。

发生新错误是因为显然我无法在MySQL中的删除表上创建子查询。

对于如何重写上述查询之一以使其有效,您有什么建议吗?

1 个答案:

答案 0 :(得分:0)

只需删除子查询即可。这是不必要的。我不确定如何在Hybernate中编写SQL代码,但我猜它会是这样的:

DELETE a 

FROM   ActiveTimes a

       JOIN a.source.stage st
       JOIN st.level.dataSource ds

WHERE  a.begin>=:from AND a.begin<=:to
       AND a.end>=:from AND a.end<=:to
       AND ds.id=:dataSource;