我有一個表rating
略有小於300k行和SQL查詢:慢SQL查詢加入
SELECT rt1.product_id as id1, rt2.product_id as id2, sum(1), sum(rt1.rate-rt2.rate) as sum
FROM rating as rt1
JOIN rating as rt2 ON rt1.user_id = rt2.user_id AND rt1.product_id != rt2.product_id
group by rt1.product_id, rt2.product_id
LIMIT 1
的問題是..它真的很慢。用limit 1
執行它需要36秒,而我需要無限制地執行它。 正如我想象的那樣,由GROUP BY
部分引起的放緩。無論從哪個表中rt1或rt2,按一列進行分組都可以正常工作。 我也嘗試過索引,我已經爲user_id,product_id,rate和(user_id,product_id)創建了索引。
EXPLAIN
對我也不太瞭解。
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE rt1 ALL PRIMARY,user_id,user_product NULL NULL NULL 289700 Using temporary; Using filesort
1 SIMPLE rt2 ref PRIMARY,user_id,user_product user_id 4 mgrshop.rt1.user_id 30 Using where
我需要這個執行一次才能生成一些數據,所以獲得最佳時間並不重要,但合理。
任何想法?
編輯。
全表架構
CREATE TABLE IF NOT EXISTS `rating` (
`user_id` int(11) NOT NULL,
`product_id` int(11) NOT NULL,
`rate` int(11) NOT NULL,
PRIMARY KEY (`user_id`,`product_id`),
KEY `user_id` (`user_id`),
KEY `product_id` (`product_id`),
KEY `user_product` (`user_id`,`product_id`),
KEY `rate` (`rate`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
請寄出兩張表的完整模式。 – mbarlocker 2013-05-09 18:08:02
它只是一張桌子,但自己加入了。 – 2013-05-09 18:11:59