現在、2 つの 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
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 を持つ他の friend_id を見つけたい場合はどうすればよいでしょうか?
たとえば、上記の SQL コマンドは、pic_id が 123、884、456 の行 0、2、および 3 を返します。これらの pic_id をループして関連する friend_id を取得するには、どの SQL コマンドを使用すればよいでしょうか? pic_id 123 の場合は 11111 になり、pic_id 456 の場合は 22222 になります。
上記を実現するために、次のコードを使用しました。効率的ではないように見えますが、遅いです。
$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
}
}
}
}
これが不明な場合は申し訳ありません。お知らせください。明確にいたします。
すべてのヘルプは大歓迎です!