2012-01-28 56 views
2

我有你表“user_follow”,“图像”,“用户”选择我和我的朋友所有的朋友,除了我们两个SQL

我的user_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%的IT部门一样的朋友,但问题是,显示我的朋友3-> 6(显示)

回答

2

什么是 'ID' 列对于?恕我直言主键应该是(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,而不是离开。

而且,也许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 

足够也许聪明,但为何要保留查询规划猜测...

相关问题