简体   繁体   中英

Accessing column from update table in subquery in mysql

I have 2 tables, "location" and "occurrence". occurrence stores events, with a creatorId and a timestamp. I'm trying to calculate an average latitude from the location table for all timestamps from location within 5 minutes of the occurrence timestamp, and put that in the occurrence latitude column.

I've tried the below and get an "unknown column 'occurrence.creatorId' in 'where clause'.

update occurrence set latitude = (
select avg(latitude) from (
select * from location where (
location.creatorId=occurrence.creatorId
and location.timestamp<occurrence.timestamp+interval 5 minute
and location.timestamp>occurrence.timestamp-interval 5 minute
)
) as test
);

My suspicion is that I'm trying to write this too much like a Java program. Can someone help my brain become more MySQL-ified?

Thanks! bugg

Try this instead:

update o
set latitude = (select avg(latitude)
                from location
                where location.creatorId=o.creatorId
                and location.timestamp<o.timestamp+interval 5 minute
                and location.timestamp>o.timestamp-interval 5 minute)
from occurrence o

You were getting the error "unknown column 'occurrence.creatorId'" because, table occurrence is not accessible to your innermost subquery. As a result all references to columns in the occurrence table from the subquery are invalid. Above query should work ok.

Try this.

update occurance o 
set o.latitude = (select avg(l.latitude) 
                   from location l where o.creatorId=l.creatorId 
                   and l.timestamp between o.timestamp-interval 5        
                   minute and o.timestamp+interval 5 minute)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM