建立基本朋友系统:获取所有朋友查询

时间:2012-01-08 23:00:41

标签: mysql sql database-design

所以我有这两个表:

user table:
id, username
10, hovercraft
11, mine_craft

friendship table:
id, user_id, friend_id
1,  10,      11

现在我有了这个SQL查询:

SELECT `friends`.`id`, 
 `friends`.`username`, 
FROM `users` AS `u` 
JOIN `friendships` AS `fs` 
ON (`fs`.`user_id` = `u`.`id`) 
JOIN `users` AS `friends` 
ON (`friends`.`id` = `fs`.`friend_id`) 
WHERE `fs`.`user_id` = '10' 
OR  `fs`.`friend_id` = '10'

在哪里我想要获取特定user_id的朋友。但是,此查询无法创建“双向”检索,因为当我提供user_id 11时,没有朋友出现。

有没有办法解决这个问题?

编辑:我忘了添加friend_id也引用用户表中的id

3 个答案:

答案 0 :(得分:1)

你的查询开始有点太深了。由于friendships表有一个可以查找用户ID的字段,然后在那里启动查询,只加入users表来选择朋友:

SELECT u."id", u."username"
FROM "friendships" AS f
JOIN "users" AS u ON f.friend_id = u."friend_id"
WHERE f."user_id" = 11

答案 1 :(得分:1)

添加,更好的版本(我认为):

select u.id, username
from user u
left join friendship f1 on u.id = f1.user_id
left join friendship f2 on u.id = f2.friend_id
where coalesce(f1.friend_id, f2.user_id, u.id) <> u.id and
    coalesce(f1.friend_id, f2.user_id, u.id) = 10

比这个查询(放在第一位):

select id, username from (
    select u.id, username, case when f.friend_id <> u.id then f.friend_id else f.user_id end as friend_id
    from user u
    join friendship f on u.id = f.user_id
    union
    select u.id, username, case when f.friend_id <> u.id then f.friend_id else f.user_id end as friend_id
    from user u
    join friendship f on u.id = f.friend_id
) t where friend_id = 10

答案 2 :(得分:0)

这是我的解决方案:困难在于正确的请求,因为朋友请求可以被交叉(如果A要求B或B要求A将以相反的方式存储在表的“to”和“from”字段中) 。让我们这样做,用户UNION和别名可以独立于下面的关系表从任何用户那里获取朋友。

  1. [朋友]表(关系):to | from | statut(待定,已确认)
  2. “to”和“from”&gt; foreign_keys约束到[users]表
  3. 以下请求始终提供所需结果! (用SESSION中的用户ID或用户ID替换%d

    SELECT
        users.userNickname,
        friends.to AS friendUser,
        friends.from AS currentUser,
        friends.statut
        FROM
        users
            INNER JOIN
            friends
            ON
            users.userId = friends.to
        WHERE
        friends.from = '%d' 
    UNION
        SELECT
        users.userNickname,
        friends.from AS friendUser,
        friends.to AS currentUser,
        friends.statut
        FROM
        users
            INNER JOIN
            friends
            ON
            users.userId = friends.from
        WHERE
        friends.to = '%d'