我遇到了Mysql查询,你能帮助我吗?
我有两张桌子:
用户
id |命名
1 | foo1
2 | foo2的
3 | foo3
帖子
id | id_user | created_at |那种
1 | 2 | 15-03-2011 |一个
1 | 2 | 14-03-2011 | b
2 | 3 | 13-03-2011 |一个
1 | 2 | 12-03-2011 | B'/ P>
我想要的是检索由创建日期排序的每个用户的最新帖子(种类无关紧要)。
我该怎么做?
谢谢你们
答案 0 :(得分:0)
在id_user上使用GROUP BY和最大发布日期?
类似的东西:
SELECT u.name, p.id_user, MAX( p.created_at )
FROM posts AS p
LEFT JOIN user AS u ON u.id
WHERE p.id_user = u.id
GROUP BY id_user
答案 1 :(得分:0)
一个可能的问题是:
SELECT
u.id,
(SELECT MAX(p.created_at) FROM posts AS p WHERE u.id = p.id_user) AS latest
FROM
user AS u;
虽然从属子查询可能不是最佳解决方案。示例输出:
users:
+------+------+
| id | name |
+------+------+
| 0 | test |
| 1 | one |
+------+------+
posts:
+------+---------+------------+------+
| id | id_user | created_at | kind |
+------+---------+------------+------+
| 0 | 0 | 2011-02-05 | a |
| 1 | 1 | 2011-02-06 | b |
| 2 | 0 | 2011-02-03 | a |
| 3 | 1 | 2011-02-02 | b |
+------+---------+------------+------+
output:
+------+------------+
| id | latest |
+------+------------+
| 0 | 2011-02-05 |
| 1 | 2011-02-06 |
+------+------------+
如果您希望获得所有用户ID的最新帖子的有序列表,您还可以在查询结尾添加ORDER BY最新DESC。