我在数据库中有许多“容器”,每个容器包含零个或多个项。每个项都有一个名称、分数、表示它被添加到容器的时间戳,以及容器ID上的外键。
我想获取顶部条目得分为5或更高的所有容器(这意味着不返回空容器)。由于容器在此实例中的行为类似于堆栈,因此具有最高“添加时间”的项被认为是“顶部”项。
目前,我使用的SQL如下:
SELECT * FROM (
  SELECT name, container_id, score
  FROM items
  ORDER BY added_time DESC
) AS temptbl
GROUP BY container_id
HAVING score >= 5这似乎给了我想要的结果,但当项目数量开始增加时,它会非常慢-在MySQL控制台上对8000个容器和10000个项目运行查询需要近6秒,这太慢了。我是不是在做一些明显低效的事情?
发布于 2010-12-11 03:13:52
尝试以下任一操作。它依赖于(container_id,added_id)的唯一性。
select *
  from (select container_id, max(added_time) as added_time
          from items
         group by container_id
       ) as topitems 
  join items on(topitems.container_id = items.container_id and 
                topitems.added_time   = items.added_time)
 where items.score >= 5;
select *
  from items a
 where score >= 5
   and (added_time) = (select max(b.added_time)
                         from items b
                        where a.container_id = b.container_id);https://stackoverflow.com/questions/4410496
复制相似问题