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

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中的每一行执行一次。

10-05 19:40