【发布时间】:2012-10-18 18:31:16
【问题描述】:
我带着一个关于 mysql 查询的问题来到这里。 我会尽量让它简单快捷(并且可以理解,因为我说法语) 这是我在 StackOverFlow 上的第一篇文章,它已经帮助我解决了各种问题,因此感谢所有社区 :)
我对 php 和 mysql 很陌生,我正在编写一个使用 php 和 mysql 的 iOS 应用程序。 在此示例中,我使用了 2 个不同的表:
-Utilisateurs(法语用户),包含:
- 姓名
- image_name(引用服务器上的 profileImage)
- 以及我在此示例中未使用的其他字段
-关注者,包含:
- user_name(静默)
- follows(此字段包含 user_name 关注的用户的名称
这是完美运行的查询
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db(db, $con);
// By this request I select the users that my current user ($_GET['userName']) follows
$result = mysql_query('SELECT user_name, follows FROM Followers WHERE user_name = "'.$_GET['userName'].'"');
while($row = mysql_fetch_array($result)){
//When I find a user that my current user follows, I select his name and the name of the user(s) that user has followed less than 2 days ago
$user = $row['follows'];
$res = mysql_query('SELECT user_name, follows, followed_on FROM Followers WHERE user_name = "'.$user.'" AND TO_DAYS(NOW()) - TO_DAYS(followed_on) <= 2');
// Now when I find a user that is followed by the user that my current user follows, I select the profile image linked to his profile
while($follow = mysql_fetch_array($res)){
$img = mysql_query('SELECT image_name FROM Utilisateurs WHERE name = "'.$follow['follows'].'"');
if(mysql_num_rows($img) != 0){
//And here I echo differents results if a profileImage has been found or not
$imgProfile = mysql_fetch_row($img);
echo $follow['user_name'].'$'.$follow['follows'].'$'.$imgProfile[0].'#';
}else{
echo $follow['user_name'].'$'.$follow['follows'].'$ #';
}
}
}
当我使用“benben”(我的当前用户)作为 $_GET['username'] 的用户名执行此查询时,一切正常,这是我在 Web 浏览器中得到的结果
Simon$Seba$#Simon$Seb$#Simon$benben$307233348488807.jpg#
在这里我可以看到:
- Simon 跟着 Seba
- Simon 已关注 Seb
- Simon 关注了本本(我),其 image_name 为 307233348488807.jpg
我将所有这些都放在我的 iOS 应用程序中的数组中,一切都正常显示并且工作正常。
但是,如果我关注了很多用户,而这些用户也关注了许多其他用户,那么就会有很多查询。 更糟糕的是,如果许多用户同时这样做。
所以我想我应该执行一些 JOINS 以执行更少的查询,但由于我是 php 和 mysql 的新手,我不知道该怎么做。我已经在比这个更简单的查询中执行了一些 JOINS,但是这个让我感到困惑。
因此,如果有人对我有一些建议或可以帮助我使用 JOINS 执行此请求,将不胜感激 :)
【问题讨论】:
-
你能在sqlfiddle.com上发布你的表结构和一些示例数据吗?