Sql 在组id上加入,以获取该表中缺少的单个id

Sql 在组id上加入,以获取该表中缺少的单个id,sql,amazon-redshift,Sql,Amazon Redshift,对于以下数据集(超级简化): t1 ext_id, tid, aid, aum, actions z1, 1, a, 100, 100 z2, 1, b, 100, 100 x1, 2, d, 200, 200 x2, 2, e, 200, 200 t2 tid, aid, aum, actions 1, a, 100, 100 1, b, 100, 100 1, c, 100, 100 2, d,

对于以下数据集(超级简化):

t1

ext_id, tid, aid, aum, actions
z1,     1,   a,   100, 100
z2,     1,   b,   100, 100
x1,     2,   d,   200, 200
x2,     2,   e,   200, 200
t2

tid, aid, aum, actions
1,   a,   100, 100
1,   b,   100, 100
1,   c,   100, 100
2,   d,   200, 200
2,   e,   200, 200
2,   f,   200, 200
我想将
t1
t2
匹配,并获取基于
tid
加入的
aid
其余部分的所有数据:

即:产出应为:

ext_id, tid, aid, aum, actions
(null), 1,   c,   100, 100
(null), 2,   f,   200, 200
我试过:

select (null) as ext_id, b.*
from #t1 a
right join #t2 b
on a.tid=b.tid
where a.aid is null
但它看起来不正确


谢谢

使用外部联接且为空运算符:

select * from t2
left join t1
using (`tid`, `aid`, `aum`, `actions`)
where ext_id is null
演示:

试试这个:

 select '(Null)' as ext_id, t2.tid, t2.aid, t2.aum, t2.actions
 from t2 left join t1 
 on t2.tid=t1.tid 
 and t2.aid=t1.aid
 where t1.tid is null and t1.aid is null
这是对我有效的正确(可扩展)答案:

select distinct b.*
from t1 a
join t2 b on a.tid=b.tid
left join t1 c on b.aid=c.aid
where c.aid is null

运行以下查询以获得所需的结果

select t1.ext_id,t2.tid,t2.aid,t2.aum,t2.actions from t1 
right join t2 
on  t1.aid= t2.aid 
where t1.ext_id is null

我认为在你的情况下,你可以利用不存在来得到你想要的

我建议如下:

select *
from t2
where not exists (SELECT 1 FROM t1 where t1.tid = t2.tid and t1.aid = t2.aid)

这是MySQL,我使用的是红移-你确定这能工作吗?我看不到
在文档中的任何地方使用
left JOIN。。。。使用。。。哪里SQL标准的所有基本特性都是空的,几乎所有的execpt一些非常奇特和有限的数据库都支持它们,RedShit也支持它们,这里是一个左连接的例子。谢谢。不幸的是,我有30多条记录(如前所述,这是一种简化的方式),所以它不适用于我正在尝试做的事情。有什么方法可以让它更具可扩展性吗?@Y.S更新了我尝试过的内容,并发布了一个答案谢谢,但这会返回
t2
中基于
tid
S的记录,这些记录在
t1
中不存在。我只需要
t1
中缺少的
t2
中的
aid
s,基于
t1
中存在的
tid
s,谢谢Khan,这与krokodilko的答案是相同的概念,但是如果还有很多其他类似的列(实际上有30多个),这是不可伸缩的@user8834780我注意到你发布了一个对你有用的答案,但这个答案可能更直观。不管怎样,很高兴你解决了。