關(guān)聯(lián)查詢(xún)的兩種實(shí)現(xiàn)方式
對(duì)于關(guān)聯(lián)查詢(xún),可以使用 join 一步到位,或拆分成兩次查表。
方式一:join 一步到位
select ... 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;
這種方式一次查詢(xún)即可獲取所有信息,效率更高。
方式二:拆分成兩次查表
-- 獲取 id SELECT ... FROM `friendships_friendship` WHERE `friendships_friendship`.`to_user_id` = 1 LIMIT 21; -- 使用 in 操作符查詢(xún) SELECT ... FROM `auth_user` T3 WHERE T3.`from_user_id` in (xxxx, xxx, xxxx) LIMIT 21;
這種方式需要兩次查詢(xún),效率較低。
mysql 關(guān)聯(lián)查詢(xún)執(zhí)行順序
對(duì)于關(guān)聯(lián)查詢(xún),mysql 會(huì)先執(zhí)行 where 條件,再進(jìn)行 join 操作。
在方式一中,會(huì)先找到 friendships_friendship.to_user_id = 1 的記錄,再進(jìn)行 join 操作。
其他注意事項(xiàng)
需要注意的是,如果表中數(shù)據(jù)量較大,使用的方式不同,執(zhí)行效率也會(huì)有很大差異。另外,拆分查詢(xún)后,需要確保兩次查詢(xún)的限制條件一致,才能得到正確的結(jié)果。
? 版權(quán)聲明
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載。
THE END