Mat*_*ins 2 postgresql join left-join
我有两个关于这个问题的表:conversations有很多messages.基本结构(只有相关列)如下:
conversations (
int id (PK)
)
create table conversation_participants (
int id (PK),
int conversation_id (FK conversations),
int user_id (FK users),
unique key on [conversation_id, profile_id]
)
create table messages (
int id (PK),
int conversation_id (FK conversations),
int sender_id (FK users),
int recipient_id (FK users),
text body
)
Run Code Online (Sandbox Code Playgroud)
对于每个对话条目,给定user_id我希望收到:
conversations.*)order by messages.id desc limit 1)messages.id desc)不幸的是,我似乎可以找到所有类似于MySQL的查询帮助,这在PostgreSQL中不起作用.我发现最接近的是StackOverflow上的这个答案给出了一个select distinct on (...)语法示例.但是,除非我做错了,否则我似乎无法以正确的方式对结果进行排序,因为我需要使用该方法进行分组约束.
所有信息都在表"消息"中,您不需要其他表:
SELECT
id,
body,
c.* -- content from conversations
FROM messages
JOIN
(SELECT MAX(id) AS id, conversation_id
FROM messages
WHERE 1 IN(sender_id, recipient_id) -- the number is the userid, should be dynamic
GROUP BY conversation_id) sub
USING(id, conversation_id)
JOIN conversations c ON c.id = messages.conversation_id
ORDER BY
id DESC;
Run Code Online (Sandbox Code Playgroud)
编辑:只需加入"对话"即可获得此表所需的数据.
| 归档时间: |
|
| 查看次数: |
5226 次 |
| 最近记录: |