Mysql多表连接以获取用户详细信息

时间:2016-04-02 19:41:51

标签: php mysql join

我有两张桌子:

表格 - 用户

userId ||  username ||  profileImage
------------------------------------
1      ||  aa       ||  aaaaa.png

2      ||  bb       ||  bbbb.png

3      ||  cc       ||  cccc.png

4      ||  dd       ||  dddd.png

表格 - 关系

relationshipId  ||  user1  ||  user2 ||  status
-----------------------------------------------
1               ||  1      ||  2    ||  0

2               ||  1      ||  3    ||  1

3               ||  1      ||  4    ||  1

4               ||  2      ||  4    ||  1

所以我想要1已发送请求和状态的所有用户(3,4)的详细信息被接受为1。

我试过的东西:

$stmt = $this->db->prepare("
SELECT users.uId
     , users.username
     , users.profilePic 
  from users
  JOIN relationship 
 WHERE (relationship.user_one_Id = :profileUserId || relationship.user_two_Id=:profileUserId) 
   AND relationship.statusCode=:statusCode
   AND users.uId != :profileUserId 
 LIMIT 6
");

$stmt->bindvalue(":statusCode", 1);
$stmt->bindparam(":profileUserId", $profileUserId);
$stmt->execute(); 

但是这个问题给了我一些行,包括那些我也不是朋友的行。那么我哪里出错了。

1 个答案:

答案 0 :(得分:0)

我不明白relationship.user_one_Id出现在哪里。我猜你打算写relationship.user1?我还假设发件人存储在user1中。在这种情况下,您的查询过于复杂:

SELECT t.uId, t.username, t.profilePic
FROM users t
INNER JOIN relationship r
    ON (t.id = r.user2
        AND r.user1 = :profileUserId
        AND r.status = :statusCode
    )
相关问题