合并两个表,按比例交错两个表的 select 查询结果
Merging two tables with interleaving the result of select queries of both tables in a proportion
我有两个table
CREATE TABLE Posts
(
Id BIGSERIAL NOT NULL,
Content TEXT NOT NULL
);
CREATE TABLE Ads
(
Id BIGSERIAL NOT NULL,
Content TEXT NOT NULL
);
我需要将这两个table按比例组合起来,应用ORDER BY
和OFFSET
。来自 Ads
1
的行 table 在来自 Posts
table 的每个 10
行中 我有什么办法可以做到这一点吗?
最后一行应该是 10 个帖子 - 1 个广告 - 10 个帖子 - 1 个广告。如何通过交错不同选择
的结果来实现合并两个tables
正常UNION
将合并所有行而不交错
SELECT * FROM (SELECT Id, Content, 'Post' AS Type FROM Posts
UNION
SELECT Id, Content, 'Ads' AS Type FROM Ads) AS sel
LIMIT 10;
一种选择是使用 row_number()
:
select id, content, type
from (
select id, content, 'post' type, (row_number() over(order by id) - 1) / 10 rn
from posts
union all select id, content, 'ads', row_number() over(order by id) - 1
from ads
)
where rn <= 1
order by rn, type desc
诀窍是将 posts
table 的行号除以 10 - 因此每组 10 个连续的行都会获得相同的排名。然后,外部查询按排名排序,然后按降序类型排序。这会将前 10 个帖子放在最前面(排名 0),然后是 1 个广告,依此类推。等级也可以用来限制组数[=13=]
我有两个table
CREATE TABLE Posts
(
Id BIGSERIAL NOT NULL,
Content TEXT NOT NULL
);
CREATE TABLE Ads
(
Id BIGSERIAL NOT NULL,
Content TEXT NOT NULL
);
我需要将这两个table按比例组合起来,应用ORDER BY
和OFFSET
。来自 Ads
1
的行 table 在来自 Posts
table 的每个 10
行中 我有什么办法可以做到这一点吗?
最后一行应该是 10 个帖子 - 1 个广告 - 10 个帖子 - 1 个广告。如何通过交错不同选择
的结果来实现合并两个tables正常UNION
将合并所有行而不交错
SELECT * FROM (SELECT Id, Content, 'Post' AS Type FROM Posts
UNION
SELECT Id, Content, 'Ads' AS Type FROM Ads) AS sel
LIMIT 10;
一种选择是使用 row_number()
:
select id, content, type
from (
select id, content, 'post' type, (row_number() over(order by id) - 1) / 10 rn
from posts
union all select id, content, 'ads', row_number() over(order by id) - 1
from ads
)
where rn <= 1
order by rn, type desc
诀窍是将 posts
table 的行号除以 10 - 因此每组 10 个连续的行都会获得相同的排名。然后,外部查询按排名排序,然后按降序类型排序。这会将前 10 个帖子放在最前面(排名 0),然后是 1 个广告,依此类推。等级也可以用来限制组数[=13=]