MySQL如何使用JOIN获取更多信息


MySQL how to grab more information with JOIN?

目前,我有两个MySQL表。

第一张表存储了朋友和他的照片之间的关系。

表1

 id  |  pic_id  |  friend_id
----------------------------
 0   |  123     |  84589
 1   |  290     |  11390
 2   |  884     |  84589
 3   |  456     |  84589
 4   |  123     |  11111
 5   |  456     |  22222

表2

第二表存储了有关图片的更多信息。。。

id   |  pic_id  |  title   |  color  |  detail
----------------------------------------------
0    |  123     | hello    |  black  |  brush
1    |  124     | world    |   red   |  paint
2    |  884     | sample   |  green  |  star

我使用JOIN获取我需要的信息。。。

但是,如果我想使用上面SQL匹配的pic_id,并找到具有相同pic_id的OTHER friend_id,该怎么办?

例如,上面的SQL命令将为我提供具有pic_id的第0、2和3行123、884、456。我应该使用哪个SQL命令来循环这些pic_id和抓取关联的friend_id?我想以11111结束pic_id 123,以22222结束pic_id456。

我使用了以下代码来完成上述操作。它看起来效率不高,但速度很慢。

$sql = "SELECT b.title, b.color, b.detail
FROM table1 a INNER JOIN table2 b
on a.pic_id = b.pic_id
WHERE friend_id = 84589";
$res = mysqli_query($link,$sql);
    if($res){
        while ($rec = mysqli_fetch_assoc($res)){
            $pic_id.=$rec['pic_id'].",";
            $arr[] = $rec;
        }
    } 
$each_id = explode(',',$pic_id);
    foreach($each_id as $key => $value){
        if ($value){
            $next_sql = "SELECT friend_id FROM table1 WHERE pic_id=".$value;
            $next_res = mysqli_query($link,$next_sql);
            if ($next_res){
                while($next_rec = mysqli_fetch_assoc($next_res)){
                    //do things
                }
            }
        }
    }       

如果不清楚,我很抱歉。请告诉我,我会澄清的。

非常感谢所有的帮助!

试试这个(更新):

SELECT a.friend_id, a.pic_id
 FROM table1 a 
  WHERE EXISTS (SELECT 1 FROM table1 t 
          WHERE t.pic_id = a.pic_id AND t.friend_id = 84589)

检查这个-http://sqlfiddle.com/#!3/91cdf/3

我认为您可以在现有联接之前通过自联接获得所需的内容。此查询将返回共享图片的friend_id的逗号分隔列表。

SELECT 
  pic_detail.title, 
  pic_detail.color, 
  pic_detail.detail,
  GROUP_CONCAT(friend_pics.friend_id) as friend_ids
FROM table1 as root_pics
JOIN table1 as freind_pics 
  USING(pic_id)
JOIN table2 as pic_details
  ON root_pics.pic_id = pic_details.pic_id OR friend_pics.pic_id = pic_details.pic_id
WHERE friend_id = 84589
GROUP BY pic_detail.pic_id