我正在创建网络服务以返回聊天和通知列表。用户可以将页码和每页显示的项目数作为输入发送,但可以返回 2 种类型的对象(从最新到最新)并且必须显示在同一个列表中。
我有两个表 chat
和 notification
CREATE TABLE chat
(
idchat serial NOT NULL,
idinterest integer NOT NULL,
idowner integer NOT NULL,
iduser integer NOT NULL,
creationdate,
editdate,
CONSTRAINT pk_chat PRIMARY KEY (idchat)
)
CREATE TABLE notification
(
idnotification serial NOT NULL,
message character varying(255) NOT NULL,
creationdate date NOT NULL,
datefinvalidite date NOT NULL,
idcompte integer NOT NULL,
idtypenotification integer NOT NULL,
sender integer NOT NULL DEFAULT 0,
CONSTRAINT pk_notification PRIMARY KEY (idnotification)
)
我想创建一个 View ,将所有聊天和通知分组,由一个 ID(idchat
或 idnotification
)、一个日期(creationdate
)和一个 bool 值 ischat
但我不知道这是否是正确的解决方案。
有问题 如果我必须返回 20 行有序消息(通知和聊天),我可以:
获取最后 10 个通知,然后最后 10 个聊天,但第 9 个聊天可能比第 11 个通知早得多
检查最新聊天的日期,如果第 20 条最新通知较旧,则只获取通知,否则......我不知道
获取 20 个最新的通知、20 个最新的聊天命令并发送给客户端,但对于同时处理许多请求的服务器来说,这可能是一项繁重的任务。
最佳答案
select idchat id, creationdate, true ischat
from chat
union all
select idnotification id, creationdate, false ischat
from notification
order by creationdate desc limit 20
这个版本可能会更快:
select *
from
(
(
select idchat id, creationdate, true ischat
from chat
order by creationdate desc
limit 20
)
union all
(
select idnotification id, creationdate, false ischat
from notification
order by creationdate desc
limit 20
)
) s
order by creationdate desc limit 20
关于web-services - 如何从具有限制和偏移量的不同表中获取和排序行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16547200/