我的表格A
包含UNIQUE (ID, FK)
组合和modified
列。
我需要将表A
的所有条目与FK
分组,当其中至少有一个条目与基于CONDITION
的{{1}}匹配时。
这就是我现在正在做的事情
modified
问题是SELECT *
FROM
(SELECT COUNT(*) AS count, FK, MAX(modified)
FROM A
GROUP BY FK) AS A
WHERE
(modified > date1 AND modifed <= date2)
提供的记录数量非常少,例如来自CONDITION
的1%的记录。我不必要地在整个桌子上运行GROUP BY
感谢大家的帮助,这是因为我已经了解到你的努力,虽然看起来多余GROUP BY
是这种情况的最佳解决方案。
答案 0 :(得分:1)
SELECT FK, MAX(modified) m
FROM A
GROUP BY FK
HAVING (m > date1 AND m <= date2)
这是Postgres模拟
http://sqlfiddle.com/#!17/2230a/6
SELECT FK, MAX(modified) AS m
FROM A
GROUP BY FK
HAVING (MAX(modified) > (now()-INTERVAL '1 DAY') AND MAX(modified) <= now())
答案 1 :(得分:1)
您可以使用HAVING
简化表达式:
SELECT FK, MAX(modified)
FROM A
GROUP BY FK
HAVING SUM(CASE WHEN modified > date 1 and modifed < date2 THEN 1 ELSE 0 END) > 0;
这不会改变性能。为此,请使用EXISTS
(或IN
):
select fk, max(modified)
from a
where exists (select 1
from a a2
where a2.fk = a.fk and a2.modified > date1 and a2.modified < date2
)
group by fk;
这会在 group by
之前过滤,因此它应该使聚合更有效率。您确实需要a(fk, modified)
上的索引。
答案 2 :(得分:0)
您不需要在group by
之前添加行where
group by
条款
SELECT COUNT(*) AS count, MAX(modified)
WHERE (modified > date1 OR modifed <= date2)
FROM A
GROUP BY FK;