我正在開發一個社交網絡跟蹤應用程序。即使連接適當的索引工作正常。但是,當我添加order by子句時,總查詢需要100倍的時間來執行。以下查詢我用於獲取twitter_users而不使用order by子句。如何通過在mysql中加入表現來改善訂單
SELECT DISTINCT `tracked_twitter`.id
FROM tracked_twitter
INNER JOIN `twitter_content` ON `tracked_twitter`.`id` = `twitter_content`.`tracked_twitter_id`
INNER JOIN `tracker_twitter_content` ON `twitter_content`.`id` = `tracker_twitter_content`.`twitter_content_id`
AND `tracker_twitter_content`.`tracker_id` = '88'
LIMIT 20
顯示行0 - 19(20總計,查詢花費0.0714秒)
但是,當我通過子句添加順序(在索引列)
SELECT DISTINCT `tracked_twitter`.id
FROM tracked_twitter
INNER JOIN `twitter_content` ON `tracked_twitter`.`id` = `twitter_content`.`tracked_twitter_id`
INNER JOIN `tracker_twitter_content` ON `twitter_content`.`id` = `tracker_twitter_content`.`twitter_content_id`
AND `tracker_twitter_content`.`tracker_id` = '88'
ORDER BY tracked_twitter.followers_count DESC
LIMIT 20
顯示行0 - 19( 20總計,查詢花費13.4636秒)
當我在它的單獨表子句執行的命令其不花費太多時間
SELECT * FROM `tracked_twitter` WHERE 1 order by `followers_count` desc limit 20
顯示行0 - 19(20總計,查詢花費0.0711秒)[FOLLOWERS_COUNT:68236387 - 10525612]
該表的創建語句如下
CREATE TABLE IF NOT EXISTS `tracked_twitter` (
`id` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`handle` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`location` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`description` text COLLATE utf8_unicode_ci,
`profile_image` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`followers_count` int(11) NOT NULL,
`is_influencer` tinyint(1) NOT NULL DEFAULT '0',
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`gender` enum('Male','Female','Other') COLLATE utf8_unicode_ci
DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `followers_count` (`followers_count`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
因此,加入由工作良好,當我執行它在其表沒有減速的查詢和訂單。那麼我該如何提高性能?
UPDATE 1
@GordonLinoff方法解決,如果我只需要結果從父表中設置。我想知道每個人的推文數(與tracked_twitter表匹配的twitter_content的計數)。我如何修改它?如果我想在推特內容上使用數學函數,我該怎麼做?
SELECT `tracked_twitter` . * , COUNT(*) AS twitterContentCount, retweet_count + favourite_count + reply_count AS engagement
FROM `tracked_twitter`
INNER JOIN `twitter_content` ON `tracked_twitter`.`id` = `twitter_content`.`tracked_twitter_id`
INNER JOIN `tracker_twitter_content` ON `twitter_content`.`id` = `tracker_twitter_content`.`twitter_content_id`
WHERE `is_influencer` != '1'
AND `tracker_twitter_content`.`tracker_id` = '88'
AND `tracked_twitter_id` != '0'
GROUP BY `tracked_twitter`.`id`
ORDER BY twitterContentCount DESC
LIMIT 20
OFFSET 0
如果刪除了「LIMIT」子句,無序查詢需要多長時間?無序結果集中的「LIMIT」基本意思是「給我20條符合我的標準的記錄」,而在有序的結果中,它意味着「找到符合我的標準的前20條記錄」,這基本上意味着你必須標識所有其中。 –
查詢中的'EXPLAIN'的輸出是什麼? – raina77ow
@ raina77ow我加了解釋圖片 – Tamizharasan