开发者

how to query names of friends from a friend's table

开发者 https://www.devze.com 2023-04-04 12:04 出处:网络
Given the following table, I\'m trying to write a query that will return the names of user 104\'s friends.

Given the following table, I'm trying to write a query that will return the names of user 104's friends.

MYSQL TABLE friends

id | requester | requestee | status
--------------------------------------
1  | 140       | 104       | 'friends'
2  | 104       | 151       | 'friends'

I tried this but it's not quite right because it returns the name of user 140 (which is correct) and the name of user 104 (which is incorrect - I wanted the name of user 151). I realize part of my problem is due to the "ON f.requester = u.id", but I'm not sure how to write the query to get what I want.

SELECT u.name
FROM users u
INNER JOIN friends f ON f.requester = u.id
WHERE (
f.requester =104
AND STATUS = 'friends'
)
OR (
f.requestee =104
AND STATUS = 'friends'
)
LIMIT 0 , 30 

Any help is appreciated. Thanks.

UPDATE: I also tried making a "bigger query" and using PHP to extract what I need. This sort of works but I'm only able to get the user IDs so far. $query = "SELECT * FROM friends WHERE requester='$userid' OR requestee='$userid' AND status='friends'"; $results = mysql_query($q开发者_JS百科uery) or die(mysql_error());

$count = 0;
while ($row = @mysql_fetch_assoc($results)){
  $count++;
  if ( !is_null($row['requester']) ) {
    $requester = $row['requester'];
    $requestee = $row['requestee'];
    if($requester == $userid)
      echo $requestee . "<br /><br />";
    else
      echo $requester . "<br /><br />";
  }
}


You're basically looking at two queries - one where 104 is the requester and the other where 104 is the requestee. A UNION query can combine these, so that you can use the result in a join or a sub select.

SELECT u.name
FROM users u
WHERE u.id IN (
    SELECT requester as friendId
    FROM friends
    WHERE requestee = 104
    AND STATUS = 'friends'
    UNION
    SELECT requestee as friendId
    FROM friends
    WHERE requester = 104
    AND STATUS = 'friends'
)
0

精彩评论

暂无评论...
验证码 换一张
取 消