问题描述:

$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'];

}

I am basically looping through all my friends, and getting information about each one.

How would I ago about optimizing this, I am aware that that it is inefficient to run this query so many times, considering there are thousands of "friends", but I'm not exactly sure how to go about optimizing it. Any help is appreciated, thanks.

网友答案:

That article in the comments is great. You're definitely going to want to figure out how to write the join yourself. Here's my attempt at writing it for you. While you're rewriting the query, you might want to not * columns from friend_requests (or any at all since you're going to use the join). Any column you pull will have to be loaded into memory so any you can avoid pulling will help out. Especially if you're PHP server and your DB server are not on the same machine (less data over the network).

Anyway, here's my shot in the dark:

$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();

quick reference: get_result()

相关阅读:
Top