2012-07-07 35 views
0

目前,我有两个MySQL表。MySQL如何通过JOIN获取更多信息?

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

表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

二表存储有关的PI​​C的详细信息...

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,并且找到其他friend_id的pic_id相同吗?

例如,上面的SQL命令会给我第0,第2和第3行的pic_id的123,884,456。我应该使用什么SQL命令循环这些pic_id并获取关联的friend_id?我想结束与11111 pic_id 123和22222 pic_id 456.

我已经使用下面的代码来完成上述。它看起来效率不高,但速度很慢。

$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 
       } 
      } 
     } 
    }  

对不起,如果这不清楚。请让我知道,我会澄清。

非常感谢所有帮助!

+0

风格的笔记(以及比风格更合理一点...)。您正在创建一个逗号分隔的pic_ids列表,就像您要在IN()子句中使用它们一样,但只是将它们分解并随后运行一个查询;在一个循环内......通常,循环内的任何查询都是巨大的红旗(即你来这里是正确的;-)。作为一个细节,你应该在构建一个数组时创建一个列表(然后使用implode()为IN()子句创建一个字符串;但是你会在答案中找到更好的建议:-) – 2012-07-07 03:07:37

+0

你的提示!你知道的越多... – 2012-07-07 03:42:27

回答

2

试试这个(更新):

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

+0

谢谢你的建议,但MySQL查询没有返回:( – 2012-07-07 03:42:06

+0

更新的查询,请检查sqlfiddle的结果 – 2012-07-07 18:23:13

0

我认为你可以得到你想要与您现有的连接前自联接什么。此查询将返回共享图片的friend_ids的逗号分隔列表。

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