0

これが私のselectクエリステートメントです:

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 クエリ ステートメントは正常に動作しますが、出力が正確に必要なものではないことを除きます。私が欲しいのは、現在のユーザーと彼のフォローからすべての投稿を選択することであり、各投稿のユーザー名は lateststatus 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
4

2 に答える 2

2

この句 -LIMIT 0,1を SQL ステートメントに追加します。これにより、結果の数が基本的に最大 1 つ (最新の投稿) に制限されます。SELECT の MySQL リファレンス マニュアルによると、 LIMIT 句は次のように定義されています。

LIMIT 句を使用して、SELECT ステートメントによって返される行数を制限できます。

また、次のような追加の order-by 句が必要になると思います: ORDER BY posts.created_at DESC

于 2013-03-31T09:38:05.127 に答える
1

表示しているユーザー ID の数に関係なく機能する 1 つのクエリを次に示します。最新のステータス変更の日付を計算し、それを結合に使用します。

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 に答える