开发者

How to query multiple tables?

What I want to achieve is to select the comments which are written only by my friends. I have the following tables.

Friends

id
my_user_id
friend_user_id

Comments

id
user_id
comment

This is how I did so far.

First find out who are my friends in the friends tabl开发者_如何学运维e:

mysql_query("SELECT friend_user_id FROM friends 
             WHERE my_user_id = $user_id ");

Then I selected the comments written only by my friends.

mysql_query("SELECT * FROM comments WHERE user_id = 'my_first_friends_id' 
             OR user_id = 'my_second_friends_id' ");

Now, this was the lame version, and it is very slow. I have millions of entries in the comments table.

What is the best solution for this problem? How to solve this in one query? And also very important to be fast.


select c.id, c.user_id, c.comment
    from Friends f
        inner join Comments c
            on f.friend_user_id = c.user_id
    where f.my_user_id = $user_id
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜