I have an SQL query on tables having a lot of rows. So this query runs for a very long time. How can I optimize this query? These tables already have indexes on id and friend_id
SELECT u.id, u.first, u.last,
group_concat(u2.first, " " , u2.last) MyFriends
FROM Users u
INNER JOIN Friends f ON f.user_id = u.id
INNER JOIN Users u2 ON u2.id = f.friend_id
GROUP BY u.id;
These are the table structures:
CREATE TABLE Users (
id int(10) unsigned NOT NULL,
first varchar(50) DEFAULT NULL,
last varchar(50) DEFAULT NULL,
city varchar(20) DEFAULT NULL,
country varchar(20) DEFAULT NULL,
Age tinyint(3) unsigned NOT NULL,
KEY users_idx_id (id))
ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE Friends (
user_id int(10) unsigned NOT NULL,
friend_id int(10) unsigned NOT NULL,
KEY idx_friends (friend_id))
ENGINE=InnoDB DEFAULT CHARSET=latin1;