一共三张表tips,tippings,comments。tippings 是中间表。tips 和 comments 是多对多的关系。tips只有两列:id,name
tippings 的create语句:
[code="sql"]
CREATE TABLE tippings
(id
INT(11) NOT NULL AUTO_INCREMENT,tip_id
INT(11) NULL DEFAULT NULL,tippable_id
INT(11) NULL DEFAULT NULL,tipper_id
INT(11) NULL DEFAULT NULL,tipper_type
VARCHAR(255) NULL DEFAULT NULL,tippable_type
ENUM('Post','Comment') NULL DEFAULT NULL,context
ENUM('tips') NULL DEFAULT NULL,created_at
DATETIME NULL DEFAULT NULL,
PRIMARY KEY (id
),
INDEX index_tippings_on_tip_id
(tip_id
),
INDEX index_tippings_on_tippable_id_and_tippable_type_and_context
(tippable_id
, tippable_type
, context
),
INDEX index_cttt
(context
, tippable_type
, tippable_id
, tip_id
)
)
[/code]
查询语句为
[code="sql"]
SELECT tips.*, COUNT(*) AS count FROM tips
LEFT OUTER JOIN tippings
ON tips.id = tippings.tip_id INNER JOIN
comments ON comments.id = tippings.tippable_id WHERE (tippings.tippable_type
= 'Comment') GROUP BY tips.id, tips.name HAVING COUNT(*) > 0 ORDER BY
count desc LIMIT 75;
[/code]
tippings 目前800多万条记录。
查询速度太慢
各位帮忙看看能不能更好的优化下
额 错了 http://asyty.iteye.com/blog/1202943
表大了就不联表咯 各种子查询
用中间表当主表 两个关联的当字表 :lol:
可以用多列索引
额 貌似比较复杂
你可慢慢研究下,之前刚整理了下mysql的优化。。。