【问题标题】:SQL - LIMITing AND filtering a join at same timeSQL - 同时限制和过滤连接
【发布时间】:2019-02-23 19:13:42
【问题描述】:

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

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、...)

【问题讨论】:

标签: sql postgresql-9.6


【解决方案1】:

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

【讨论】:

  • 谢谢。这正是我一直在寻找的。 :)
  • 一年前我自己发现了它,当时我非常需要它。
  • 过滤条件不是s.col1 != t.col2 ?
猜你喜欢
  • 1970-01-01
  • 2012-01-11
  • 2022-10-12
  • 1970-01-01
  • 2020-10-12
  • 1970-01-01
  • 2016-03-02
  • 1970-01-01
  • 2011-06-25
相关资源
最近更新 更多