我有一张名为 的表图片 其中有属性名称img_ID
这是主键 ,
还有一个名为 的表收藏 其中有两个属性 'img_ID' & user_ID
... img_ID
作为外键 到图像和user_ID
担任 外键 给用户
现在我需要来自 的详细信息图片 全部img_ID
来自 收藏 在哪里 user_ID
是一些 x 值
我可以这样做,顺便说一句,我正在使用 PHP & mySQL
$gett = mysql_query("SELECT img_ID FROM favorites WHERE user_ID='".$variable."'");
if( mysql_num_rows($gett) > 0 )
{
while( $steps = mysql_fetch_assoc($gett) )
{
$res = mysql_query("SELECT * FROM images WHERE img_ID='".$steps['img_ID']."' ORDER BY img_Date");
if( mysql_num_rows($res) > 0 )
{
while( $result= mysql_fetch_assoc($res) )
{
echo $result['img_Name'];
echo $result['img_Desc'];
echo $result['img_ext'];
}
else
echo "no images were found";
}
}
else
echo "no favorites were found";
伪代码就像
RUN QUERY
for each img_ID where user_ID is this
RUN QUERY
for each img_ID
perform DISPLAY
这种方法有一个缺陷和一个倒退
FLAW = 时间戳上的订单被销毁
back-draw =嵌套循环中有一个查询..
问题:这一切都可以通过查询来完成吗?如果是,那么如何?
最佳答案
使用连接:
select
i.*
from
favorites f
join images i on f.img_id = i.img_id
where
f.user_id = <user id>
另外,更改您的代码以使用 mysqli并准备好带有绑定(bind)变量的语句,以提高性能并消除 sql 注入(inject)攻击的威胁。
关于php - 从具有多对多关系的表中获取结果的单个 SQL 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4241561/