【发布时间】:2021-05-28 21:14:36
【问题描述】:
假设我们使用左连接或内连接通过某种条件连接两个表(A 和 B)
WITH
a(id, x) AS (VALUES
(0, 'a'),
(1, 'a'),
(2, 'b')
),
b(id, y) AS (VALUES
(10, 'a'),
(20, 'a'),
(30, 'b')
),
pairs AS (
SELECT a.id AS a_id, b.id AS b_id
FROM a LEFT JOIN b ON a.x=b.y
)
SELECT * FROM pairs; -- how to modify this query to return the expected result?
结果将是 5 行 (2 * 2 + 1 * 1) 现在最困难的部分是:每个表中的 id 只能在结果中出现一次。
a_id|b_id|
----|----|
0| 10|
->0| 20| -- a_id=0 can be picked only once
1|->10| -- b_id=10 can be picked only once
1| 20|
2| 30|
-- so the expected result is:
a_id|b_id|
----|----|
0| 10|
1| 20|
2| 30|
-- UPDATE: alternative result could be:
a_id|b_id|
----|----|
0| 20|
1| 10|
2| 30|
【问题讨论】:
-
我尝试使用子查询和
DISTINCT ON语法,但这并没有给我预期的结果 -
为什么不
(0,20),(1,10),(2,30)? -
这是另一个满足结果的选项。取决于顺序,但总的来说没关系。只是 ID 不能重复
-
我会更改配对的代码。这可能吗?
-
@S-Man 是的,但这有什么不同吗?
标签: postgresql join distinct distinct-values