MySQL社区

 找回密码
 注册

QQ登录

只需一步,快速开始

扫一扫,访问微社区

搜索
查看: 7869|回复: 3
打印 上一主题 下一主题

三表关联,查询中按聚合函数的结果排序,如何优化?

[复制链接]
跳转到指定楼层
1#
发表于 2011-10-27 10:44:54 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
一共三张表tips,tippings,comments。tippings 是中间表。tips 和 comments 是多对多的关系。tips只有两列:id,name
tippings 的create语句:

  1.     CREATE TABLE `tippings` (  
  2.         `id` INT(11) NOT NULL AUTO_INCREMENT,  
  3.         `tip_id` INT(11) NULL DEFAULT NULL,  
  4.         `tippable_id` INT(11) NULL DEFAULT NULL,  
  5.         `tipper_id` INT(11) NULL DEFAULT NULL,  
  6.         `tipper_type` VARCHAR(255) NULL DEFAULT NULL,  
  7.         `tippable_type` ENUM('Post','Comment') NULL DEFAULT NULL,  
  8.         `context` ENUM('tips') NULL DEFAULT NULL,  
  9.         `created_at` DATETIME NULL DEFAULT NULL,  
  10.        PRIMARY KEY (`id`),  
  11.        INDEX `index_tippings_on_tip_id` (`tip_id`),  
  12.        INDEX `index_tippings_on_tippable_id_and_tippable_type_and_tip_id` (`tippable_id`, `tippable_type`, `tip_id`),  
  13.        INDEX `index_cttt` (`context`, `tippable_type`, `tippable_id`, `tip_id`)  
  14.    )
复制代码


查询语句为:
  1.     SELECT  tips.*, COUNT(*) AS count FROM `tips` LEFT OUTER JOIN tippings  
  2.     ON tips.id = tippings.tip_id  INNER JOIN  
  3.     comments ON comments.id = tippings.tippable_id WHERE (tippings.tippable_type  
  4.     = 'Comment')  GROUP BY tips.id HAVING COUNT(*) > 0 ORDER BY  
  5.     count desc LIMIT 75;  
复制代码
tippings 目前800多万条记录。
查询速度太慢
怎么设置索引能使按那个聚合函数count(*) 排序时不产生 Using temporary,当然更改my.cnf当中tmp_table_size的大小先除外考虑。
各位帮忙看看能不能更好的优化下
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友 微信微信
收藏收藏 分享淘帖 顶 踩
2#
 楼主| 发表于 2011-10-27 12:44:07 | 只看该作者
看来无重赏,无勇夫了。哎,为之奈何??
3#
发表于 2011-10-31 09:49:42 | 只看该作者
首先表tippings里的索引重复严重,需要优化。
建议为,根据你实际情况再定:
  INDEX `index_tippings_on_tip_id` (`tip_id`),  
  INDEX `index_tippings_on_tippable_id (`tippable_id),
  INDEX `index_cttt` (`context`)

如果你确实需要GROUP BY tips.id HAVING COUNT(*) > 0(最好根据业务能优化掉) ,建议先对表tips做这样的操作,再和tippings 表 LEFT OUTER JOIN 效果较好。

然后多使用下explain看看执行计划。
您需要登录后才可以回帖 登录 | 注册

本版积分规则

QQ|申请友链|小黑屋|Archiver|手机版|MySQL社区 ( 京ICP备07012489号   
联系人:周生; 联系电话:13911732319

GMT+8, 2024-5-18 05:43 , Processed in 0.066952 second(s), 23 queries , Gzip On.

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表