0

如何优化此查询?获取 10 行需要 2-3 秒。

SELECT users.user_id, users.user_name, users.user_display_name,
(SELECT COUNT(tweet_id) FROM tweets WHERE tweet_user_id = users.user_id AND tweet_status = 1) AS  user_tweets_count,
(SELECT COUNT(tweet_reply_id) FROM tweets_reply tr JOIN tweets t ON t.tweet_id = tr.tweet_reply_tweet_id WHERE tweet_reply_user_id = users.user_id AND t.tweet_status = 1 AND tr.tweet_reply_status = 1) AS user_replies_count
FROM users
JOIN tweets ON tweets.tweet_user_id = users.user_id
JOIN tweets_reply ON tweets_reply.tweet_reply_user_id = users.user_id
WHERE (tweets_reply.tweet_reply_status = 1 AND tweets.tweet_status = 1)
GROUP BY users.user_id
ORDER BY (user_tweets_count + user_replies_count) DESC
LIMIT 10
4

1 回答 1

0
   SELECT users.user_id, users.user_name, users.user_display_name, 
   COUNT(tweets.tweet_id) AS user_tweets_count, 
   COUNT(tweets_reply.tweet_reply_id) AS user_replies_count
   FROM users
   JOIN tweets ON tweets.tweet_user_id = users.user_id
   JOIN tweets_reply ON tweets_reply.tweet_reply_user_id = users.user_id
   WHERE (tweets_reply.tweet_reply_status = 1 AND tweets.tweet_status = 1)
   GROUP BY users.user_id
   ORDER BY (user_tweets_count + user_replies_count) DESC
   LIMIT 10

希望这可以帮助。

于 2013-10-04T17:00:38.287 回答