我有3个表,即HeroAcademy
,Hero
和HeroMission
。我想从3个表中选择 academyID 列表。
isActive IS true
和lastSeen BETWEEN :start AND :end
。lastSeen
在各自的表中订购。我试图寻找更好的解决方案。暂时,我正在使用:(简要示例)
SELECT DISTINCT academyID FROM (
SELECT academyID, lastSeen FROM HeroAcademy WHERE ... UNION
SELECT DISTINCT academyID, lastSeen FROM Hero WHERE ... ORDER BY lastSeen UNION
SELECT DISTINCT academyID, lastSeen FROM HeroMission WHERE ... ORDER BY lastSeen
) ORDER BY lastSeen
有没有更好的解决方案?看来我的查询非常基本且超慢......期待任何天才查询。 ^ _ ^
答案 0 :(得分:1)
我想你想要:
SELECT DISTINCT ON (academyID) academyID
FROM ( (SELECT DISTINCT ON (academyID) academyID, lastSeen
FROM HeroAcademy
WHERE ...
ORDER BY academyID, lastSeen DESC
) UNION ALL
(SELECT DISTINCT ON (academyID) academyID, lastSeen
FROM Hero
WHERE ...
ORDER BY academyID, lastSeen DESC
) UNION ALL
(SELECT DISTINCT ON (academyID) academyID, lastSeen
FROM HeroMission
WHERE ...
ORDER BY academyID, lastSeen DESC
)
) a
ORDER BY academyID, lastSeen;
注意:
WHERE
子句,这可以利用每个表上(academyId, lastSeen)
的索引。union
和select distinct
两个级别。DISTINCT ON
可以更好地获取最新(或最近)的记录。根据{{1}}子句,它可以利用索引。