Wednesday, 28 August 2013

Delete from subquery

Delete from subquery

I am using Hibernate in my application. Currently I am trying to execute
the following query:
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)
But I get an error: Column 'id' in field list is ambiguous. This feels
normal, because the created SQL query looks like this:
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=?
)
)
If I change the query to:
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)
I get another error: You can't specify target table 'active_times' for
update in FROM clause.
I am not very experimented with JPQL(or HQL) so I do not understand why
the query looks like that in the first example.
The new error occurs because apparently I cannot make a subquery on the
delete table in MySQL.
Do you have any suggestions on how can I rewrite one of the above queries
in order to make it work?

No comments:

Post a Comment