我在Postgres中有一个简单的表格,用于存储用户的个人信息:
id | author_id | reciever_id | content | status_id | created_at
-----+-----------+-------------+----------+-----------+------------------------
1 | 1 | 74 | 1 to me | 1 | 2015-07-31 13:51:49+03
159 | 81 | 74 | 81 to me | 0 | 2015-07-31 13:51:49+03
160 | 74 | 81 | I to 81 | 0 | 2015-07-31 13:51:49+03
161 | 81 | 74 | 81 to me | 0 | 2015-07-31 13:51:49+03
我希望得到"对话"从这张桌子。这个术语意味着我必须只有一行来自满足条件的这些行"获取作者是我的#34;的消息。这些行将作为会话标题呈现在视图中。
我有查询(为我获取所有消息):
select * from messages
<joing table with user's name>
where reciever_id = 74
但它给了我
id | author_id | reciever_id | content | status_id | created_at
-----+-----------+-------------+----------+-----------+------------------------
1 | 1 | 74 | 1 to me | 1 | 2015-07-31 13:51:49+03
159 | 81 | 74 | 81 to me | 0 | 2015-07-31 13:51:49+03
161 | 81 | 74 | 81 to me | 0 | 2015-07-31 13:51:49+03
其中第三行是额外的。如何在查询中只获得满足条件的一行?
答案 0 :(得分:0)
您需要使用公共列加入两个表。它应该是
select * from messages as t1 inner join users as t2
on t1.author_id=t2.user_id
where t1.reciever_id = 74
答案 1 :(得分:-1)
您可以在请求结束时使用“限制1”来获取第一个结果。
您可能希望使用order by指定哪一个是第一行。