LEFT JOIN与主查询的相对值

时间:2016-02-10 20:31:21

标签: mysql sql join left-join

我有两张桌子:用户友谊。例如:

用户表:

id | user  | email   | website
1  | Igor  | i@o.com | stack.com
2  | Lucas | a@i.com | overflow.com
3  | John  | j@w.com | www.com

友谊表(当status = 2表示他们是朋友时):

id | friend1 | friend2 | status
1  | Igor    | John    | 2
2  | Lucas   | Igor    | 2
3  | John    | Lucas   | 2

我执行以下操作以选择朋友(其中$user是当前用户登录的):

SELECT friend1, friend2 
FROM friendship 
WHERE (friend1 = '$user' OR friend2 = '$user') AND status = 2

但我也想在用户表中选择用户数据,因此,我会这样做:

SELECT friend1, friend2 
FROM friendship 
LEFT JOIN users 
ON user = **friend** 
WHERE (friend1 = '$user' OR friend2 = '$user') AND status = 2

在上面的ON条款中,我在朋友这个词中留下了星号,因为你看我怀疑的地方。我想只选择表用户中的数据而不是当前用户记录的数据($user),我知道我应该用来验证CASE是否等同于登录用户但是我在这种情况下不知道该怎么做。

3 个答案:

答案 0 :(得分:2)

我认为你可以使用

select * from user where 
user in (
    select friends1 from friendship where friend2='$user' and status=2
    union all
    select friends2 from friendship where friend1='$user' and status=2
)

我添加了左连接示例

select u.* from (
    select friends1 f from friendship where friend2='$user' and status=2
    union all
    select friends2 f from friendship where friend1='$user' and status=2) a
left join user u on a.f=u.user

答案 1 :(得分:2)

这适用于您的示例数据(假设您想要友谊中的两个朋友的用户信息):

SELECT f.friend1, u1.id, u1.email, u1.website, f.friend2, u2.id, u2.email, u2.website
FROM friendship f
INNER JOIN users u1
ON f.friend1 = u1.user 
INNER JOIN users u2
ON f.friend2 = u2.user
WHERE (friend1 = '$user' OR friend2 = '$user')
AND f.status = 2

答案 2 :(得分:1)

使用简单的JOIN即可轻松完成此操作,只需包含您的逻辑:

SELECT
    U.id,
    U.user,
    U.email,
    U.website
FROM
    Friendship F
INNER JOIN Users U ON
    (U.user = F.friend1 AND F.friend1 <> '$user') OR
    (U.user = F.friend2 AND F.friend2 <> '$user')
WHERE
    F.friend1 = '$user' OR F.friend2 = '$user'