我需要一个解决以下问题的方法。我有两张桌子:
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、3、3、.)
发布于 2018-09-19 15:10:38
在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中的每一行执行一次横向子查询。
https://stackoverflow.com/questions/52408787
复制相似问题