Insane query time (mySQL)

Hello,
I’ve noticed that one of my page has been EXTREMELY slow…
I checked every function and i was able to determine where my problem is.

here is the function:

(Some stats: FRIENDS table has 30,000 entries and USERS table has 1000)


function getNext( $n, $sort)
    {
        $id = $this->user->getID();
        $next = array();
        
        
        if($sort)
        {
            $result = mysql_query("SELECT id FROM users WHERE id NOT IN(SELECT id2 FROM friends WHERE id1=$id) AND id != $id ORDER BY packageclass DESC, dailyPoints DESC LIMIT $n");
        }
        else
            $result = mysql_query("SELECT id FROM users WHERE id NOT IN(SELECT id2 FROM friends WHERE id1=$id) AND id != $id ORDER BY RAND() LIMIT $n");
            
        if(!$result)
        {
            echo "error:".mysql_error();
        }
        else
        {
            while($row = mysql_fetch_array($result))
            {
                $next[] = $row['id'];
            }
        }
        return $next;
    }    


I’m guessing that this query is just killing the server.
it takes about 30-60 seconds to finish.

What should i do ?