我有两个表,Users(id, username)
和Posts(id, user_id, content)
。我想列出它们的摘要,我想列出所有用户和每个用户的第一篇文章。如何在一个查询中实现这一点?
我尝试了类似的东西。
SELECT Users.*, Posts.content
FROM Users, Posts
WHERE Posts.user_id=T_Users.id
但是它会返回每个用户的所有帖子(我不能在当然只返回一个用户的尾部添加LIMIT 1
)。
一些样本记录:
用户表:
id username
1 test1
2 test2
帖子表:
id user_id content
1 1 This is a test1's content.
2 1 This is another test1's content.
3 2 This is a test2's content.
我想要结果:
Users.id Users.username Posts.content
1 test1 This is a test1's content.
2 test2 This is a test2's content.
答案 0 :(得分:2)
以下是获取每位用户最新记录的一种方法我假设最新记录将被视为最低帖子ID
SELECT u.*, p.content
FROM Users u
join Posts p on p.user_id=u.id
join (select user_id ,min(id) id from Posts group by user_id ) p1
on (p.id = p1.id and p.user_id = p1.user_id )
答案 1 :(得分:1)
试试这个
select min(x.id) as Id,x.user_id,x.content from(
select p.id,p.user_id,p.content from Users u inner join Posts p
on u.id=p.user_id and u.gender=1
)x group by x.user_id
答案 2 :(得分:0)
您是否尝试过group by子句。
SELECT Users.*, Posts.content
FROM Users, Posts
WHERE Posts.user_id=T_Users.id GROUP BY Posts.user_id