我在转换需要将多个值返回到内部联接的子查询时遇到了很多麻烦,因为只有最新版本的最里面的结果应该返回。我尝试过搜索和浏览各种答案,但我找不到修复方法。下面有点简化,但显示了我想要的东西,但根本不起作用:
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
(信息在修订版之间通常没有变化,但大多数文档至少有一些。)我可以使用多个子查询,每列一个,但这很慢而且很愚蠢。
天真地,我把它翻译成:
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
但显然,当我只想要每项工作的最新信息数据时,每个工作会返回多个结果,每个匹配信息行一个结果。
我看到一个答案暗示开始像from (select max(date) from workupdates where workupdates.work = works.id) wu inner join works
,但在我的情况下,这只是给了我一个破解的查询,其中数据库声称工作.id不存在。我已经看过并尝试了很多不同的变化 - 我不知道这么多类似的查询可能结构如此不同 - 但我还没有运气,我的大脑也相当疲惫。
答案 0 :(得分:0)
尝试使用以下内容替换第二个查询中的第一个LEFT JOIN
:
LEFT JOIN
(
SELECT aa.*
FROM workupdates aa
INNER JOIN
(
SELECT work, MAX(date) AS maxdate
FROM workupdates
GROUP BY work
) bb ON aa.work = bb.work AND aa.date = bb.maxdate
) b ON works.id = b.work
这将仅为每个工作ID加入最近的 workupdates行。
答案 1 :(得分:0)
我认为您可以使用修改版作为“统治表”并将其余部分附加在其中:
SELECT works.id, title, version, date, pages, uploaded, uri
FROM workupdates
JOIN info ON info.id=workupdates.info
JOIN works ON workupdates.work = works.id
WHERE workupdates.date =
(SELECT MAX(date) FROM workupdates WHERE work = works.id)
;
即使这是次优的,因为JOIN将在日期过滤之前发生。
或者转动桌子并拥有工作规则,可能更好:
SELECT works.id, title, version, date, pages, uploaded, uri
FROM works
JOIN workupdates ON (workupdates.work = works.id
AND workupdates.date =
(SELECT MAX(date) FROM workupdates WHERE work = works.id))
JOIN info ON info.id=workupdates.info
;
在加入工作日和作品时应该可以保存一个迭代,但是现在还没有找到我(而且可能是我在做梦): - (