加入两个条件与conditon

时间:2017-02-10 21:37:04

标签: php sql database laravel-5

我有两张桌子:

users
- id
- fname
- lname
- is_online

friendships
- friendA (references users)
- friendB (references users)
- status (1 means they are friends)

我想查询在线用户的所有朋友。

2 个答案:

答案 0 :(得分:0)

SELECT
t1.*
FROM users t1
WHERE
t1.id IN (
    SELECT
    friendB
    FROM friendships
    WHERE
    friendA = CURRENT_USER_ID
    UNION
    SELECT
    friendA
    FROM friendships
    WHERE
    friendB = CURRENT_USER_ID
)
t1.is_online = 1
AND NOT t1.id = CURRENT_USER_ID

答案 1 :(得分:0)

Select 
    Unique(id) 
from 
    users outer join 
    friendships where 
        ((friendA = id and friendB = ID_TO_QUERY) or 
         (friendA = ID_TO_QUERY and friendB = id) and status = 1) 
        and is_online = true 
        and id /= ID_TO_QUERY