MySQL How to select friends from a friendship table?
Hi I have a simple database for storing friendship, with just two columns person_a, person_b , denoting that person_a and person_b are friends. From a big list like this what query 开发者_如何学JAVAshould I run to get say get all friends of 'sam'. Thank you.
Use a UNION:
SELECT person_b
FROM friendship
WHERE person_a = 'sam'
UNION
SELECT person_a
FROM friendship
WHERE person_b = 'sam'
May be try like this,
SELECT person_a, person_b
FROM friendship
WHERE person_a = 'sam' or person_b = 'sam'
Use the query like this, after that
if(person_a=='sam') {
$frnd = $rowfetch["person_b"];
} else if(person_b=='sam') {
$frnd = $rowfetch["person_a"];
}
You might want to try something like
SELECT *
FROM users u INNER JOIN
(
SELECT CASE
WHEN person_a = yourid THEN
person_b
ELSE person_a
END person_id
FROM FRIENDSHIPS
WHERE person_a = yourid
OR person_b = yourid
) myFriends ON u.userID = myFriends.person_id
精彩评论