SQL 按一列连接和排序两个表
SQL JOIN and ORDER two tables by one column
我有两个 SQL 表,Activity
和 Notifications
,在客户端我有一个显示两者合并的视图。但是,此视图需要分页(普通用户可能在这里有 100 个对象)并按 createdAt
列排序,这两个表都有。
如何编写一个 SQL 查询以垂直连接两个表,按 createdAt
排序,最后按 limit/offset 排序?
编辑:
架构:
Activity(id, createdAt, media, userId)
Notifications(id, createdAt, userId, text)
预期结果(按降序创建于):
id | createdAt | media | userId | text
---------------------------------------
1 | ... | t.jpg | 56 | null
...
10 | ... | null | 45 | test
查看您的示例,您似乎需要联合表:
select id, createdAt, media, userId, Null as text from Activity
union all
select id, createdAt, Null as media, userId, text from Notifications
order by createdAt
limit 100
我有两个 SQL 表,Activity
和 Notifications
,在客户端我有一个显示两者合并的视图。但是,此视图需要分页(普通用户可能在这里有 100 个对象)并按 createdAt
列排序,这两个表都有。
如何编写一个 SQL 查询以垂直连接两个表,按 createdAt
排序,最后按 limit/offset 排序?
编辑:
架构:
Activity(id, createdAt, media, userId)
Notifications(id, createdAt, userId, text)
预期结果(按降序创建于):
id | createdAt | media | userId | text
---------------------------------------
1 | ... | t.jpg | 56 | null
...
10 | ... | null | 45 | test
查看您的示例,您似乎需要联合表:
select id, createdAt, media, userId, Null as text from Activity
union all
select id, createdAt, Null as media, userId, text from Notifications
order by createdAt
limit 100