php - Select each first record with id in another table's result -
i have 2 tables, users(id, username)
, posts(id, user_id, content)
. want list summary of them which, want list users , first post of each user. how can realize in 1 query?
i tried like.
query
select users.*, posts.content users, posts posts.user_id=t_users.id
but return posts each user (i cannot add limit 1
@ tail of course returns 1 user).
some sample records:
users table:
id username 1 test1 2 test2
posts table:
id user_id content 1 1 test1's content. 2 1 test1's content. 3 2 test2's content.
and want result:
users.id users.username posts.content 1 test1 test1's content. 2 test2 test2's content.
here 1 approach latest record per user assume latest record considered minimum post id
select u.*, p.content users u join posts p on p.user_id=u.id join (select user_id ,min(id) id posts group user_id ) p1 on (p.id = p1.id , p.user_id = p1.user_id )
Comments
Post a Comment