web-services - 如何从具有限制和偏移量的不同表中获取和排序行?

标签 web-services list postgresql

我正在创建网络服务以返回聊天和通知列表。用户可以将页码和每页显示的项目数作为输入发送,但可以返回 2 种类型的对象(从最新到最新)并且必须显示在同一个列表中。

我有两个表 chatnotification

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(idchatidnotification)、一个日期(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/

相关文章:

postgresql - 具有编辑距离的组

sql - 创建 Postgres 交叉表查询并计算列之间的差异

oracle - 通过 PL/SQL 访问 HTTPS Web 服务的问题

sql-server - 将数据从SAP导出到SQL Server

.net - .NET中的WCF是什么?

web-services - 微服务架构 : Cross Service data sharing

list - 避免在 Erlang 中将数字转换为字符

c# - 将与类列表的列表项匹配的字典键加入新列表 - C#

c# - 改变 List<Point> 项的值

perl - 从 postgresql 函数中检索异常消息