3

我正在使用 codeigniter 和 mysql 并应用在具有 200 MB 内存和 1 GB CPU 的服务器中,在表 a(索引:idx_cat)中有 40.000 行,类别中有 44 行(索引:primary),我需要获得前 4 名在每个类别中,这是我的查询

SELECT id,title,preview,created,image,dummy,name 
FROM
 (
 select news.id AS id,news.title AS title,preview,created,news.image,category_id ,
         @num := if(@cat = category_id, @num + 1, 1) as row_number,
         @cat := category_id as dummy,
        name,d_order
 from news use index (idx_cat) inner join category b on category_id=b.id
 where 
    news.category_id in (9,8,3,35,57,56,15,58,41,42,43,44,34,52,37,38,36,11) and
    news.status = 1 
 having row_number <= 4 
 order by dummy ASC,news.created desc
 ) as a 
order by d_order ASC,created DESC



id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   PRIMARY     <derived2>  ALL     NULL    NULL    NULL    NULL    **29639**   Using filesort
2   DERIVED     b   ALL     PRIMARY,id  NULL    NULL    NULL    **44**  Using where; Using temporary; Using filesort
2   DERIVED     news    ref     idx_cat     idx_cat     **4**   b.id    846     Using where    

并获得了其他 6 个简单的加入,例如

   select id,name from others a inner join b on a.cat_id = b.id

该网站的加载速度非常快,大约 1 秒或 2 秒,但如果在另一个选项卡中打开,而另一个选项卡的加载速度有点慢,比如 5-7 秒。

奇怪的是 cpu 使用率达到 100 % 并且内存使用率得到了 +_ 40 MB 来完成一个视图(我确定没有其他打开)但 CI PROFILING 它说只是用户 4MB。

我也有加载模型、帮助程序和按需库,只有两个(url 和表单)我放在自动加载文件中。

如果我打开 5 到 10 个窗口,它会说内存不足,你们有什么建议吗?这让我发疯 -_-

4

1 回答 1

2

要减小内部选择结果的大小,请将字段的选择和连接移动named_order外部选择

SELECT id,title,preview,created,image,dummy,name,d_order FROM
     (
 select news.id AS id,news.title AS title,preview,created,news.image,category_id ,
         @num := if(@cat = category_id, @num + 1, 1) as row_number,
         @cat := category_id as dummy
 from news use index (idx_cat) 
 where 
    news.category_id in (9,8,3,35,57,56,15,58,41,42,43,44,34,52,37,38,36,11) and
    news.status = 1 
 having row_number <= 4 
 order by dummy ASC,news.created desc
 ) as a inner join category b on category_id=b.id
order by d_order ASC,created DESC

可能行数仍然很大,但我们减少了内存。您选择的方式需要处理整个新闻表,然后删除不需要的行,这是非常昂贵的计算。如果您仅使用 news.id、cat.id 和 minimun 字段进行新闻预选,可能会更有效,因此新闻正文重字段不在重选择范围内。

SELECT id,c.title,c.preview,created,c.image,dummy,name,d_order FROM
     (
 select news.id AS id,category_id ,
         @num := if(@cat = category_id, @num + 1, 1) as row_number,
         @cat := category_id as dummy
 from news use index (idx_cat) 
 where 
    news.category_id in (9,8,3,35,57,56,15,58,41,42,43,44,34,52,37,38,36,11) and
    news.status = 1 
 having row_number <= 4 
 order by dummy ASC,news.created desc
 ) as a 
    inner join category b on category_id=b.id
    inner join news c on a.id = c.id
    order by d_order ASC,created DESC

可能我有一些 sintax 错误,但在这里写起来有点困难,而且我没有要测试的数据。希望你明白我看到问题的地方。

于 2012-11-19T12:56:03.093 回答