SQL - 同时限制和过滤连接

SQL - LIMITing AND filtering a join at same time

我需要解决以下问题的方法。 我有两个表:

ids from new user (got by subquery)

+------------+
|  user_id   |
+------------+
| 1          | 
| 4          | 
| 5          |
+------------+

users (table with all users)
+------------+
|  user_id   |
+------------+
| 1          | 
| 2          | 
| 3          |
| 4          |
| 5          |
| ...        |
+------------+

我需要加入这两个表。每个新用户需要 正好 3 个与其他用户的连接。

例如:

+----------+------+
| new_user | user |
+----------+------+
| 1        | 2    |
| 1        | 3    |
| 1        | 4    |
| 4        | 1    |
| 4        | 2    |
| 4        | 3    |
| 5        | 1    |
| 5        | 2    |
| 5        | 3    |
+----------+------+

问题是将条目限制为 正好 3 并排除冗余条目(如 1|1、3|3、...)

在 PostgreSQL 中,您可以使用 lateral 查询在子查询中检索有限数量的行。

我不知道您的主查询或子查询的确切结构,但它应该如下所示:

select t.*, ls.*
  from main_table t,
  lateral ( -- lateral subquery
    select * from secondary_table s
      where s.col1 = t.col2 -- filtering condition, if needed
      fetch first 3 rows only -- limit to a max of 3 rows
  ) ls;

main_table.

中每行执行一次横向子查询