First of all, this question is not answered earlier since the thread about error 1093 shows a simple subquery. In my case, I'm doing a lookup for the next record referencing the main table. Please don't tag it as a duplicate without first reading the whole question.
I need to update the records of a table which has a wrong date (1970-01-01), using the next record's data (according to the gkey field, which is consecutive int primary key).
So, if I do this query:
SELECT aa.gkey,
aa.course_date,
(select course_date from BI.fact_training_event_tbl bb where bb.gkey = (
select min(cc.gkey)
from BI.fact_training_event_tbl cc
where cc.gkey > aa.gkey)) as next_date
from BI.fact_training_event_tbl aa
where course_date = '1970-01-01'
It brings the records correctly, as expected:
gkey course_date next_date
==== =========== =========
4103 1970-01-01 2017-03-23
4884 1970-01-01 2017-03-22
5047 1970-01-01 2017-03-23
I now need to update the course_date field with next_date, but if I try running the following:
update BI.fact_training_event_tbl aa
set course_date =
(select course_date from BI.fact_training_event_tbl bb where bb.gkey = (
select min(cc.gkey)
from BI.fact_training_event_tbl cc
where cc.gkey > BI.fact_training_event_tbl.gkey))
where course_date = '1970-01-01'
I get the error:
Error Code 1093. You can't specify target table 'BI.fact_training_event_tbl' for update in FROM clause
I tried doing what is recommended here: MySQL Error 1093 - Can't specify target table for update in FROM clause, nesting the query inside another:
update BI.fact_training_event_tbl as zz
set course_date =
(select course_date from
(select course_date from BI.fact_training_event_tbl as bb where bb.gkey = (
select min(cc.gkey)
from BI.fact_training_event_tbl as cc
where cc.gkey > gkey)) as aa )
where course_date = '1970-01-01'
but all I get is set the date_course as null, and not the next_date.
And if I try referencing the main table like this:
where cc.gkey > BI.fact_training_event_tbl.gkey
or
where cc.gkey > zz.gkey
It says: Unknown column BI.fact_training_event_tbl.gkey or zz.gkey.
Any ideas on how I can pull this off?