如何使用SQL查询优化while循环?

时间:2015-09-13 01:02:18

标签: php mysql optimization

$id = $user['id']; // the ID of the logged in user, we are retrieving his friends
$friends = $db->query("SELECT * FROM friend_requests WHERE accepted='1' AND (user1='".$id."' OR user2='".$id."') ORDER BY id DESC");

while($friend = $friends->fetch_array()) {
    $fr = $db->query("SELECT id,profile_picture,age,full_name,last_active FROM users WHERE (id='".$friend['user1']."' OR id='".$friend['user2']."') AND id != '".$id."'")->fetch_array(); 
    echo $fr['age'];     
}

我基本上会遍历所有朋友,并获取有关每个朋友的信息。

我如何才能优化这一点,我知道多次运行此查询是低效的,考虑到有成千上万的朋友",但我并不完全确定如何优化它。感谢任何帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

评论中的那篇文章很棒。你肯定想要弄清楚如何自己编写联接。这是我尝试为你写的。当您重写查询时,您可能不希望*来自friend_requests的列(或任何根据您将要使用该连接的列)。您拉的任何列都必须加载到内存中,因此任何可以避免拉动的列都会有所帮助。特别是如果您是PHP服务器并且您的数据库服务器不在同一台机器上(通过网络的数据较少)。

无论如何,这是我在黑暗中的镜头:

$id = $user['id'];

$friends = $db->prepare("
    SELECT
        freq.* 
        ,users.id AS users_id
        ,users.profile_picture
        ,users.age
        ,users.full_name
        ,users.last_active
    FROM friend_requests freq
    INNER JOIN users u ON users.id IN (freq.user1,freq.user2) AND freq.id != u.id
    WHERE
        freq.accepted='1'
        AND ? IN (freq.user1,freq.user2
    ORDER BY freq.id DESC");
if($friends) {

    $friends->bindParam("s",$id);

    if($friends->execute()) {
        // get_result() only works if you have the MySQL native driver. 
        // You'll find out real quick if you don't
        $myFriends = $friends->get_result();

        while($row = $myFriends->fetch_assoc()) {
            echo $row['age'];     
        }
    }
}
else {
    printf("SQL Error: %s.<br>\n", $friends->error);
}
// cleanup
$friends->close();

快速参考:get_result()