MySQL JOIN 查詢性能優化:獲取用戶粉絲信息,使用 JOIN 還是拆分查詢更優?

MySQL JOIN 查詢性能優化:獲取用戶粉絲信息,使用 JOIN 還是拆分查詢更優?

mysql join 查詢性能優化:使用 join 還是拆分查詢?

對于獲取特定用戶的粉絲信息的查詢,可以使用 join 操作或拆分查詢。以下分析對比了兩種方法的性能:

join 查詢 (方式一)

select     `friendships_friendship`.`id`,     `friendships_friendship`.`from_user_id`,     `friendships_friendship`.`to_user_id`,     `friendships_friendship`.`created_at`,     t3.`id`,     t3.`password`,     t3.`last_login`,     t3.`is_superuser`,     t3.`username`,     t3.`first_name`,     t3.`last_name`,     t3.`email`,     t3.`is_staff`,     t3.`is_active`,     t3.`date_joined` from     `friendships_friendship`     left outer join `auth_user` t3 on (         `friendships_friendship`.`from_user_id` = t3.`id`     ) where     `friendships_friendship`.`to_user_id` = 1 limit     21;

join 查詢僅執行了一次查詢,雖然使用了連接操作,但只連接了滿足條件的記錄。因此,整體效率不會比拆分查詢差多少。

拆分查詢 (方式二)

此方法分為兩步:

步驟 1: 獲取好友關系表中滿足條件的記錄。

select     `friendships_friendship`.`id`,     `friendships_friendship`.`from_user_id`,     `friendships_friendship`.`to_user_id`,     `friendships_friendship`.`created_at` from     `friendships_friendship` where     `friendships_friendship`.`to_user_id` = 1 limit     21;

步驟 2: 使用步驟 1 獲得的 from_user_id,在用戶表中查詢用戶信息。

SELECT     T3.`id`,     T3.`password`,     T3.`last_login`,     T3.`is_superuser`,     T3.`username`,     T3.`first_name`,     T3.`last_name`,     T3.`email`,     T3.`is_staff`,     T3.`is_active`,     T3.`date_joined` FROM     `auth_user` T3 WHERE     T3.`from_user_id` in (xxxx, xxx, xxxx) LIMIT     21;

拆分查詢分兩步進行,需要分別執行兩次查詢,效率稍低。

總的來說,對于這種類型的查詢,使用 join 查詢的效率會略高于拆分查詢。

mysql 執行順序

mysql 的執行順序是先執行 where 子句,然后再執行 join 操作。因此,對于方式一的查詢,mysql 會先找到 friendships_friendship 表中 to_user_id=1 的記錄,再與 auth_user 表進行 join 操作。

? 版權聲明
THE END
喜歡就支持一下吧
點贊5 分享