【问题标题】:How to get 2 id from tow column and get all records from another table如何从两列中获取 2 个 id 并从另一个表中获取所有记录
【发布时间】:2015-05-20 13:18:58
【问题描述】:
I have tow table as below 

FWTable

mid uname   gender  avatar          email           psw     dob         city
1   User 1  Male    cat.jpg         user1@gmail.com psw1    2015-05-18  Ahmedabad
2   User 2  Female  Koala.jpg       user2@gmail.com psw2    2015-05-15  Jamnagar
3   User 3  Male    Desert.jpg      user3@gmail.com psw3    2015-04-25  Porbandar
4   User 4  Female  Jellyfish.jpg   user4@gmail.com psw4    2015-06-11  Jamnagar
5   User 5  Male    Penguins.jpg    user5@gmail.com psw5    2015-07-10  Jamnagar
6   User 6  Female                  user6@gmail.com psw6    2015-05-12  Jamnagar

好友列表

fid     mid friend_id   friend_status
1       1   2           1
2       1   3           0
3       2   4           0
1002    3   4           1
1003    5   1           1

当用户1(mid 1)在线时,我想显示那些朋友喜欢的。

2   User 2  Female  Koala.jpg       user2@gmail.com psw2    2015-05-15  Jamnagar
5   User 5  Male    Penguins.jpg    user5@gmail.com psw5    2015-07-10  Jamnagar

【问题讨论】:

  • 您使用的是哪个 DBMS?到目前为止,您尝试过什么?
  • SQL Server 2012,当用户 1(mid 1) 处于活动状态时,我想 id 2,5
  • 为什么用户 3 不在结果中?他是用户 1 的朋友
  • 不,friend_status=1(朋友)|| friend_status=1(不是朋友)
  • "friend_status=1 (朋友) ||friend_status=1 (非朋友)" 也许friend_status=1 ||朋友状态=0 ?

标签: sql sql-server sql-server-2012 left-join


【解决方案1】:

试试这个:

select t1.*
from FWTable t1
join FriendsList t2 on t1.mid = t2.mid
where t2.friend_id = 1
and status = 1

union

select t1.*
from FWTable t1
join FriendsList t2 on t1.mid = t2.friend_id
where t2.mid = 1
and status = 1

【讨论】:

    【解决方案2】:
    with all_friendships as (
        --making a distinct list of all friendships, for both directions
        select mid as the_user, friend_id as the_friend 
            from FriendsList 
            where friend_status = 1
        union
        select friend_id as the_user, mid as the_friend 
            from FriendsList 
            where friend_status = 1
    )
    
    select mid, uname, gender, avatar, email, psw, dob, city
    from all_friendships
    inner join FWTable on the_friend = mid
    where the_user = 1
    

    看起来你想展示双向的友谊,不仅是 mid 1 的朋友,还有 mid 1 的朋友。这应该可以解决这个问题。

    【讨论】:

      猜你喜欢
      • 2020-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多