我在我的數據庫中的兩個表一個是保持用戶信息(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))
")
}
不怕大寫字母...... – Lix
我的建議是提取每個ID的朋友列表,並用php做出常見的朋友之間的匹配,當涉及操縱數據時,MSQL比其他編程語言慢。 – jcho360
@ jcho360不好的建議。數據庫的規模往往比這種內存方式要好得多。數據庫在處理數據時不會「比其他編程語言慢」,實際上,如果使用正確的話,它們通常要快得多。 –