Reputation: 1853
Currently, I have two MySQL tables.
First table stores relation between the friend and his picture.
TABLE 1
id | pic_id | friend_id
----------------------------
0 | 123 | 84589
1 | 290 | 11390
2 | 884 | 84589
3 | 456 | 84589
4 | 123 | 11111
5 | 456 | 22222
TABLE 2
Second table stores more information about the pic...
id | pic_id | title | color | detail
----------------------------------------------
0 | 123 | hello | black | brush
1 | 124 | world | red | paint
2 | 884 | sample | green | star
I use JOIN to grab the information I need...
But what if I want to use the pic_id's that were matched by the above SQL and find OTHER friend_id's with the same pic_id?
For example, the above SQL command will give me rows 0, 2, and 3 with pic_id's 123, 884, 456. What SQL command should I use to loop through these pic_id's and grab associated friend_id's? I want to end up with 11111 for pic_id 123 and 22222 for pic_id 456.
I have used the following code to accomplish the above. It does not look efficient and is slow though.
$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
}
}
}
}
Sorry if this is unclear. Please let me know and I will clarify.
All help is greatly appreciated!
Upvotes: 0
Views: 74
Reputation: 27467
Try this (Updated) :
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)
check this - http://sqlfiddle.com/#!3/91cdf/3
Upvotes: 2
Reputation: 18290
I think you can get what you want with a self-join before your existing join. This query will return a comma-seperated list of friend_ids which share the pic.
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
Upvotes: 0