将SELECT变量连接到不同的表列中按照建议

时间:2013-09-09 18:28:49

标签: mysql sql pdo

我正在尝试将一个特定SELECT变量的结果连接到另一个表的不同列中。

user_friends表:

+-------------------------------------------+
|    friend_id | friend_one | friend_two    |
+-------------------------------------------+

用户表:

+------------------+
|   uiD | username |
+------------------+

以下查询检索我的粉丝所关注的随机朋友并向我推荐,目前它只是在恢复他们的uiD(id)。 我不确定如何将这两个表连接在一起并获得下面的GROUP BY possible_friend以连接到users表。

$sth = $this->db->prepare("
                            SELECT friend_two AS possible_friend
                            FROM user_friends
                            WHERE friend_one IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD) 
                            AND friend_two NOT IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD)
                            AND NOT friend_two = :uiD
                            GROUP BY possible_friend
                            ORDER BY RAND()
                            ");
$sth->execute(array(':uiD' => $uiD));

$data = $sth->fetch();
return $data;

例如,我是用户10。

uiD = 10:用户名:Jonathan

uiD = 20:用户名:Gabriel

uiD = 30:用户名:Lisa

uiD = 40:用户名:Emily

我是以Jonathan身份登录的,这是跟随Gabriel的,但是Jonathan并没有关注Lisa和Emily。 然后它应该在div上显示。

遵循建议: 艾米丽或丽莎

通过上面的查询,我只能随机获取他们的ID,但我无法使用user_friends表中的possible_friend从users表加入Username。

我尝试了以下内容。

    $sth = $this->db->prepare("
                                SELECT F.friend_two AS possible_friend, U.username
                                FROM user_friends F, users U
                                WHERE F.friend_one IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD) 
                                AND F.friend_two NOT IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD)
                                AND NOT F.friend_two = :uiD
                                GROUP BY possible_friend
                                ORDER BY RAND()
                                ");
    $sth->execute(array(':uiD' => $uiD));

    $data = $sth->fetch();
    return $data;

但它只返回另一个用户名,因为我无法将U.username与possible_friend连接。

更新版本 - 工作版本:

    SELECT F.friend_two AS possible_friend, U.username, U.uiD, U.photo
    FROM user_friends F, users U
    WHERE F.friend_one IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD) 
    AND F.friend_two NOT IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD)
    AND NOT F.friend_two = :uiD
    AND U.uiD NOT IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD) 
    AND U.photo NOT IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD) 
    GROUP BY possible_friend
    ORDER BY RAND()

1 个答案:

答案 0 :(得分:1)

SELECT U.uiD, U.username
FROM users U
WHERE U.uiD NOT IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD) 
AND U.uiD NOT IN (SELECT friend_two FROM user_friends WHERE friend_one = :uiD)
ORDER BY RAND()