I’m having a lot of trouble converting a subquery that would need to return multiple values into an inner join, due to the constraint that only the most recent version of the innermost results should be returned. I’ve tried searching and browsing various answers, but I can’t find the fix. Below is a bit simplified but shows what I want, and doesn’t work at all:
select
works.id as w_id,works.name as w_name,author,publisher,
(select name as auth from creators where author=id),
(select name as pub from creators where publisher=id),
(select version,
(select pages,uploaded,uri from info where id=workupdates.info)
from workupdates where work=works.id order by date desc limit 1)
from works
(Info is often unchanged between revisions, but most documents have at least a few.) I could use multiple subqueries, one per column, but that’s slow and stupid.
Naively, I translated it to:
select
works.id as w_id,works.name as w_name,developer,publisher,
(select name as dev from creators where developer=id),
(select name as pub from creators where publisher=id),
version,pages,uploaded,uri
from
works
left join workupdates on workupdates.work = works.id
left join info on info.id=workupdates.info
But obviously, that returns multiple results for each work, one for each matching info row, when I only want the most recent info data for each work.
I saw one answer suggesting beginning like from (select max(date) from workupdates where workupdates.work = works.id) wu inner join works but in my case that just gave me a broken query where the DB claims works.id doesn’t exist. I’ve seen and tried a LOT of different variations – I had no idea that so many similar queries could be structured so differently – but I’ve had no luck yet and my brain is rather frazzled.
I think that you might use worksupdates as ‘ruling table’ and attach the rest there:
Even if this is sub-optimal, since the JOINs would take place before the filtering on date.
Or pivoting the tables around and having works rule, maybe better:
It ought to be possible to save an iteration when joining worksupdates and works, but it’s not coming to me at the moment (and it might be I’m dreaming things up) 🙁