2013-04-07 37 views
0

這裏是我的表結構(fun_users)取從表幫助朋友的細節需要

id first_name last_name email passkey place profession self_des profile_img user_type active last_login reg_date reported_banned 

與我的友誼表

id user_id friend_id status date_request from_ip 

這裏是利用獲取的登錄信息查詢IM用戶朋友

SELECT `fun_friends`.`id` as fid, `fun_users`.`id` as uid, `fun_users`.`first_name`, `fun_users`.`profile_img`, `fun_users`.`profession`, `fun_users`.`place` FROM (`fun_friends`) JOIN `fun_users` ON `fun_users`.`id`=`fun_friends`.`friend_id` WHERE (`fun_friends`.user_id= '".$_SESSION['user_row_id']."' AND `fun_friends`.`status` =1) OR (`fun_friends`.friend_id= '".$_SESSION['user_row_id']."' AND `fun_friends`.`status` =1) 

結果是

fid uid first_name  profile_img      profession        place 
11 47 Agnii thumbs/2013-03-311364721555.jpg  Software engineer         somewhere 

查詢返回登錄用戶的詳細信息,而不是他的朋友詳細信息。誰能幫我 ?

回答

1

下面的查詢使用了一個子查詢,它可以獲取特定用戶的所有朋友。表fun_users與子查詢連接兩次,因爲子查詢上有兩列依賴於它。

SELECT a.id AS FID, 
     IF(a.user_ID = 'user_row_id_HERE', c.id, b.id) AS UID, 
     IF(a.user_ID = 'user_row_id_HERE', c.first_name, b.first_name) AS first_name, 
     IF(a.user_ID = 'user_row_id_HERE', c.last_name, b.last_name) AS last_name, 
     IF(a.user_ID = 'user_row_id_HERE', c.profile_img, b.profile_img) AS profile_img, 
     IF(a.user_ID = 'user_row_id_HERE', c.profession, b.profession) AS profession, 
     IF(a.user_ID = 'user_row_id_HERE', c.place, b.place) AS place 
FROM 
     (
      SELECT id, user_ID, friend_ID 
      FROM friendship 
      WHERE 'user_row_id_HERE' IN (user_ID, friend_ID) AND 
        status = 1 
     ) a 
     INNER JOIN fun_users b 
      ON a.user_ID = b.id 
     INNER JOIN fun_users c 
      ON a.friend_ID = c.ID 

所以問題出現了,這條線會發生什麼?

IF(a.user_ID = 'user_row_id_HERE', c.id, b.id) AS UID 

基本上,它測試對於user_ID從子查詢中的值,如果它等於當前用戶。如果碰巧相等,則將返回表fun_users c的列,反之亦然。

爲了進一步獲得更多的知識有關加入,請訪問以下鏈接: