tags:

views:

51

answers:

3

If i have two users one users have many posts in post table i.e

postid, post, userid, time(i.e timestamp)

and I have another table for friends i.e

id, friendid, userid, friend_sinc(i.e timestamp)

Now I want that users friend should see the posts of user1 after the date on which he added the user1 as friend. Not the posts older than the date on he added him as friend. How can I done it in single MySQL query?

A: 

This would look up all posts from people after they became friends with user 12:

select     *
from       Posts p
join       Friends f
on         p.userid = f.friendid
and        p.time >= f.friend_since
where      f.userid = 12
Andomar
it is giving me the following problem that user12 is also unable to see its own older posts but can see newer posts...........!! and other problem is that if user2 has 4 friends and 1 post it is showing it for 4 times.....i.e 1. post 1 2. post 1 3. post 1
testkhan
A: 
SELECT p.*
FROM post p, friend f
WHERE p.userid = f.userid AND p.time >= f.friend_sinc;

Edit: I guess it could be interpreted either way as which persond id is which, but the point is clear.

unholysampler
it is giving me the following problem that user1 is also unable to see its older posts but can see newer posts...........!! and other problem is that if user2 has 4 friends and 1 post it is showing it for 4 times.....i.e 1. post 12. post 13. post 1
testkhan
Are you talking about user1 trying to see it's own posts? Should be using a different query as it is trying to do a different thing.Use DISTINCT to remove duplicates.
unholysampler
A: 

With a union

select p.* from posts p where p.userid = <my_user_id> 
union
select p.* from posts p, friends f where 
p.userid = f.friendid and 
f.userid = <my_user_id> and 
p.time >= f.friend_since

Or you consider yourself to be your own friend, that is, there is an entry in friend with friendid = <my_user_id> and userid = <my_user_id> and friend_since = <date user was created>, and then the second query works and return your own post as well. I don't think you get duplicates.

ewernli
it is giving me the following error------------------------------------------------------------------mysql_fetch_array(): supplied argument is not a valid MySQL result resource------------------------------------------------------------------
testkhan
Query is conceptually ok, but you need to use p.* instead of * to have the union working. If you don't want the union, use the trick I mentioned, that is, to have a user be its own friend.
ewernli
You will also probably want to order them by date. If you use the union, you will need a query like "select u.* from ( select p.* from ... union select p.* from ... ) u order by u.time ".
ewernli