开发者

How to select the first post using mySQL

This is my code ( you can edit it ) :

SELECT * FROM posts WHERE posts.user_id = 1 OR posts.user_id = 2

How to select the f开发者_运维问答irst post of user 1 and 2 ?

How to select the first post using mySQL


select user_id, min(post_id) as FirstPostID
from posts
where user_id in (1, 2)
group by user_id


SELECT user_id, MIN(post_id)
FROM posts
WHERE user_id IN (1, 2)
GROUP BY user_id


SELECT user_id, post_id
FROM posts
GROUP BY user_id
ORDER BY post_id asc;

Above query would give you all the first post for all the users. Slight difference from the previous solutions.


The existing answers can be improved, as they don't match the question:

"select the first post of user 1 and 2"

Selecting just the post ID requires you issue a 2nd query to get the post data.

This avoids a 2nd query be issued to get the post data:

 SELECT * FROM posts WHERE ID in (
   select min(id)
   from   posts
   where  user_id in (1,2)
 );

Even if you just want the ID; the group by clause is also unnecessary:

   select min(id)
   from   posts
   where  user_id in (1,2)
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜