选择我和我的所有朋友,除了我们两个SQL


Select all my and my friend friends except us both SQL

我有三个表"user_follow"、"images"answers"users"

我的用户id:3我的朋友user_id:6

我需要查询来选择我和我的朋友的所有朋友及其用户名和图片1) 不要互相展示2) 重复好友显示为1

我的问题是:

    $sql = "SELECT u.username, i.image, u.id
            FROM users u
            LEFT JOIN user_follow f ON u.id = f.follow_id
            LEFT JOIN images i ON u.id = i.user_id
            WHERE f.user_id = 6 OR f.user_id = 3
            GROUP BY u.id
            ORDER BY f.date DESC";

结果是:

[user_both_follow] => Array
    (
        [0] => Array
            (
                [username] => Kolxoznik1
                [image] => 
                [id] => 1
            )
        [1] => Array
            (
                [username] => 7777
                [image] => 
                [id] => 8
            )
        [2] => Array
            (
                [username] => 6666
                [image] => flw3utn9igiqh7dtt2o61ydf8_174.jpeg
                [id] => 6
            )
        [3] => Array
            (
                [username] => 8888
                [image] => 
                [id] => 7
            )
    )

我的查询工作在50%,它将相同的朋友分组,但问题是显示我的朋友3->6(显示)

"id"列的作用是什么?IMHO主键应该是(user_id,follow_id)。。一个简单的AND f.follow_id != 3 and f.follow_id != 6应该可以修复您的查询。

可能简化为:

WHERE f.user_id IN(3,6) AND f.follow_id NOT IN (3,6)

此外,您可能希望(RIGHT) JOIN user_follow而不是left。

此外,也许MySQL足够聪明,可以对此进行优化,但我想知道EXPLAIN是否对该查询和有所不同

        SELECT u.username, i.image, u.id
        FROM user_follow f
        JOIN users u ON u.id = f.follow_id
        LEFT JOIN images i ON u.id = i.user_id
        WHERE f.user_id IN(3,6) AND f.follow_id NOT IN(3,6)
        GROUP BY u.id
        ORDER BY f.date DESC

也许足够聪明,但为什么要让查询计划器猜测。。。