这是我的选择查询语句:
select distinct posts.*, user_status.status_content
from posts left join user_status on
user_status.user_id = posts.user_id
where posts.user_id
= $userid or posts.user_id in
(select follower from follower where follower.user_id = $userid) order by posts.created_at desc;
我的select查询语句工作正常,但输出不是我想要的。
我想要的是从当前用户和他的以下选择所有帖子,每个帖子的用户名是他们最新的status content
,状态由用户更新,我想只从表中选择最新的状态内容,那么如何我可以吗?
帖子表:
+------------+------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| user_id | bigint(20) | NO | MUL | NULL | |
| content | text | NO | | NULL | |
| created_at | datetime | YES | | NULL | |
+------------+------------+------+-----+---------+----------------+
user_status表:
+----------------+--------------+------+-----+-------------------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+--------------+------+-----+-------------------+-------+
| user_id | bigint(20) | NO | MUL | NULL | |
| status_content | varchar(225) | YES | | Hello World | |
| created_date | timestamp | NO | | CURRENT_TIMESTAMP | |
+----------------+--------------+------+-----+-------------------+-------+
用户可以更新其状态,因此user_status表中会有多条记录。
我的选择查询可能会输出如下:
I feel like s**t today!!!!
Hello world
2013-03-28 22:34:14
-----------------------------
I don't feel very good today
Hello world
2013-03-28 22:34:14
我想要的是,假设I feel like s**t today
是最新状态,所以输出应该如下:
I feel like s**t today!!!!
Hello world
2013-03-28 22:34:14
答案 0 :(得分:2)
将此子句 - LIMIT 0,1
添加到SQL语句中。这基本上将结果数量限制为最多一个(这将是最新的帖子)。根据{{3}},LIMIT子句定义为:
LIMIT子句可用于约束SELECT语句返回的行数。
我还想象你需要一个额外的order-by子句 - 类似于:ORDER BY posts.created_at DESC
。
答案 1 :(得分:1)
这是一个无论您正在查看的用户ID数量多少都可以使用的查询。它计算最近状态更改的日期,并将其用于连接:
select distinct posts.*, user_status.status_content
from posts left join
user_status
on user_status.user_id = posts.user_id left join
(select user_id, max(created_at) as maxdate
from user_status
) usmax
on usmax.user_id = user_status.user_id and usmax.maxdate = user_status.create_at
where posts.user_id = $userid or
posts.user_id in (select follower from follower where follower.user_id = $userid)
order by posts.created_at desc;