【发布时间】:2020-04-02 07:38:17
【问题描述】:
我正在尝试使用 Postgres SQL 进行案例连接,我希望在第一个匹配的案例之后停止搜索
select *
from
table1 a
left join table2 b
on a.cond1 = b.cond1
and case when a.cond2 = b.cond2 and a.cond3 = b.cond3
then 1
when a.cond4 = b.cond4
then 1
else 0
end = 1
目的是如果 cond2 和 cond3 匹配就停止,只使用 table2 中匹配的行,否则尝试在 cond4 上匹配。但是,结果是保留满足这两个条件的行。我的 SQL 查询中有错误吗?
示例:
table1
id, cond1, cond2, cond3, cond4
1, 1, 1, 1, 1
2, 1, 0, 1, 1
3, 0, 1, 1, 0
4, 1, 1, 0, 0
table2
cond1, cond2, cond3, cond4, tag
1, 1, 1, 1, apple
1, 1, 0, 1, banana
结果
id, tag
1, apple
2, banana
3, null
4, null
但我要加入额外的 1、香蕉
【问题讨论】:
-
请添加示例样本数据和预期输出。
-
在
ON子句中使用AND/OR构造而不是case表达式通常会更好。 -
@jarlh 您能否详细说明在此示例中将如何完成?谢谢!
-
您的查询正在执行您要求它执行的操作。您需要使用“join”(或inner join)而不是“left join”(“left outer join”的缩写)。
-
@belayer 我得到 1,apple 和 1,banana 结果,但我只想要 1,apple,不管它是内连接还是左连接
标签: sql postgresql join case