0

这是我的选择查询语句:

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;

我的选择查询语句工作正常,只是输出不是我真正想要的。我想要的是从当前用户及其关注者中选择所有帖子,每个帖子的用户名都是最新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    |                |
+------------+------------+------+-----+---------+----------------+

用户状态表:

+----------------+--------------+------+-----+-------------------+-------+
| 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
4

2 回答 2

2

将此子句添加LIMIT 0,1到您的 SQL 语句中。这基本上将结果的数量限制为最多一个(这将是最新的帖子)。根据SELECT 的 MySQL 参考手册,LIMIT 子句定义为:

LIMIT 子句可用于限制 SELECT 语句返回的行数。

我还想你需要一个额外的 order-by 子句——比如:ORDER BY posts.created_at DESC.

于 2013-03-31T09:38:05.127 回答
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;
于 2013-03-31T15:42:47.683 回答