[英]improving a friends list query : counting the mutual friends
我的數據庫中有兩個表,一個用於保存用戶信息(users_table),另一個用於跟蹤朋友
users_table:
id username avatar
1 max max.jpg
2 jack jack.jpg
friends_table:
id u1_id u2_id
1 1 2
2 1 3
在每個用戶個人資料中,我顯示他/她的朋友列表
這是我的查詢
select u.id,
u.username,
u.avatar
from friends_table f
join users_table u on f.u1_id = u.id || f.u2_id = u.id
where u.id <> $profile_id
and (f.u1_id = $profile_id || f.u2_id = $profile_id)
此查詢選擇個人資料所有者的朋友($ profile_id)
並使用用戶表加入它們以獲取每個朋友的用戶名和頭像
現在我想要計算每個朋友和個人資料所有者之間的共同朋友是否可以在一個查詢中進行此操作,或者我應該為每個成立的朋友做一些長而且可能很慢的查詢(這只是一個示例,它可能有一些語法錯誤):
foreach ( $friends_list_query_resul as $qr ){
$friend_id = $qr['id'];
$mutual_count = mysql_query
( "select count(*) from friends_table where
($u1_id = $friend_id || $u2_id = $friend_id )
&&
( $u1_id IN ( SELECT `u1_id`,`u2_id` from friends_table where
($u1_id = $profile_id || $u2_id = $profile_id ) )
||
$u2_id IN ( SELECT `u1_id`,`u2_id` from friends_table where
($u1_id = $profile_id || $u2_id = $profile_id ) )
")
}
您的第一個查詢也可以寫成:
select distinct u.id,
u.username,
u.avatar
from users_table u where u.id in
(select case when u1_id=$profile_id then u2_id else u1_id end
from friends_table f where case when u1_id=$profile_id
then u1_id else u2_id end =$profile_id);
共同的朋友查詢可以以類似的方式編寫為單個查詢:
select u.id, (select count(f.id) from friends f where
case when f.u1_id=u.id then u2_id else u1_id end in
(select distinct case when u1_id=$profile_id then u2_id else u1_id end
from friends where case when u1_id=$profile_id then u1_id else u2_id
end =$profile_id)
and u1_id=u.id or u2_id=u.id and
(u1_id <> $profile_id and u2_id <> $profile_id))
as mutual_frnds from user u where u.id <> $profile_id;
但您可能希望在使用前對其中任何一個進行性能測試。
您只需要一個查詢:
select id, username, avatar, -- ...
(
select count(*)
from friends_table f1
inner join friends_table f2 on f1.u2_id = f2.u1_id and f2.u2_id = f1.u1_id
where f1.u1_id = users_table.id
)
as mutual_friend_count
from users_table
子查詢的含義是:
給我用戶參與的“朋友的朋友”關系的計數,使得第一朋友關系的目標是第二朋友關系的源,並且第二朋友關系的目標是第一朋友關系的源。一。
首先,我不明白為什么如此復雜的查詢來檢索用戶的朋友...應該通過這個查詢簡單地實現:
select u.id,
u.username,
u.avatar
from friends_table f
left join users_table u on f.u2_id = u.id
where f.u1_id = $profile_id
說明:登錄用戶是id與f.u1_id
相同的f.u1_id
。 因此,我們只選擇id為f.u2_id
朋友。
然后,為了統計我朋友的共同朋友,我們可以使用這樣的查詢:
select count(*) as mutual_count, f.u1_id as mutual_friend_id
from friends_table f
where f.u1_id IN (select f.u2_id from friends_table where f.u1_id = {$profile_id})
其中$ profile_id是登錄用戶的ID ...
它是否正確?
我決定為表中的每個朋友關系添加兩行。
id u1_id u2_id
1 10 20
2 20 10
它使過程更容易,更快捷。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.