sql - 加入默认值但不想要叉积

标签 sql postgresql

我在三个字段上连接两个表。我遇到的问题是,如果 a.baz 不在 b.baz 中,我需要使用表 b 中的默认行。问题是有些会在 b 中有一个匹配,但也有一个默认值,这会导致我不想要的交叉产品。

select a.foo, a.bar, a.baz, b.fee, b.fie
from a
join b
on a.foo = b.foo
and a.bar = b.bar
and ((a.baz = b.baz) or b.baz = 'DEFAULT')

当前输出:

foo  bar  baz   fee   fie 
bob  doe  NYC   500   200 
bob  doe  DEFUALT 100 100 
john doe  DEFAULT 100 100 
jane doe  NYC   500   500

期望的输出:

foo  bar  baz   fee   fie 
bob  doe  NYC   500   200 
john doe  DEFAULT 100 100 
jane doe  NYC   500   500

示例数据:

a: foo bar baz 鲍勃纽约市 约翰·多伊纽约 jane doe 纽约市

b: foo bar baz fee fie 鲍勃·多伊纽约市 500 200 bob doe 默认值 100 100 约翰·多伊 CHI 300 200 约翰·多伊 默认 100 100 jane doe NYC 500 100

最佳答案

您必须添加一个 NOT EXISTS 以便在匹配 时排除具有 baz = 'DEFAULT'b 记录a.baz = b.baz 也存在:

select a.foo, a.bar, a.baz, b.baz, b.fee, b.fie
from a
join b
on a.foo = b.foo and a.bar = b.bar and ((a.baz = b.baz) OR b.baz = 'DEFAULT')
where not exists (select 1
                  from b as b1
                  where a.foo = b1.foo and
                        a.bar = b1.bar and 
                        b.baz = 'DEFAULT' and
                        b1.baz = a.baz)

Demo here

关于sql - 加入默认值但不想要叉积,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36310176/

相关文章:

java - 我们如何知道 Spring Boot 应用程序是否正在使用连接池

java - 如何获取 java.sql.ResultSet 的大小?

mysql - 为了从 MySQL 中提取表的较大子集,索引、表顺序如何影响查询速度?

sql - 用SQL显示表的结构

sql - 如何从 PostgreSQL 中没有任何条件的表中删除前几条记录?

sql - 如何使用 nextval() 在字符串中插入包含其自己 ID 的行

mysql - 在 MySQL 中声明具有多个 JOIN 表的变量

SQL 通过滑动窗口记录出现次数

postgresql - 在 Postgresql 中查询精确的 json 键匹配(正是这些键)

ruby-on-rails-3 - Heroku + Rails + PostgreSQL 问题