我正在试图找出如何执行JOIN,其中我返回a.ssan = c.ssn
下面的结果集(查询1)中的所有记录:
查询1:
SELECT
a.memno,
a.name,
a.addr1,
a.addr2,
a.city,
a.state,
a.zip,
a.sex,
a.lname,
a.ssan,
b.addr1 as old_addr1,
b.addr2 as old_addr2,
b.city as old_city,
b.state as old_state,
b.zip as old_zip,
b.timec
FROM Lib1.Table1 a, Lib1.Table2 b
WHERE
a.memno = b.memno and
b.groupid = 'P2' and
b.type = 'B' and
b.datec = 20131206 AND
(a.addr1 <> b.addr1 or
a.addr2 <> b.addr2 or
a.city <> b.city or
a. state <> b.state or
a.zip <> b.zip)
表C字段:
SSN
DATEC
TIMEC
PRINT_OLD
PRINT_NEW
我正在为NEW和OLD地址生成邮件合并文档,以提醒成员他们帐户上的地址更改。制作新地址信件时,我在TABLEC
上运行插入,设置除PRINT_OLD
以外的所有字段的值。示例数据将是:
SSN: 123456789;
DATEC: 20131206;
TIMEC: 133000;
PRINT_NEW: 2013-12-06-13.30.00.965000;
PRINT_OLD: NULL;
然后几天后,当打印旧地址字母时,
我需要在T JOIN
上运行上面的第一个查询和TABLEC
,以显示PRINT_OLD字段 NULL 的那些记录,表示已经打印了新的地址信那天,但旧地址信没有。
任何人都可以帮我解决这个问题吗?在数据库查询方面,我不是最强的。
答案 0 :(得分:1)
你可以这样做:
SELECT *
FROM tableC c
INNER JOIN (
SELECT a.memno,
a.NAME,
a.addr1,
a.addr2,
a.city,
a.STATE,
a.zip,
a.sex,
a.lname,
a.ssan,
b.addr1 AS old_addr1,
b.addr2 AS old_addr2,
b.city AS old_city,
b.STATE AS old_state,
b.zip AS old_zip,
b.timec
FROM Lib1.Table1 a
INNER JOIN Lib1.Table2 b ON a.memno = b.memno
WHERE b.groupid = 'P2'
AND b.type = 'B' AND b.datec = 20131206
AND (
a.addr1 <> b.addr1 OR a.addr2 <> b.addr2
OR a.city <> b.city OR a.STATE <> b.STATE
OR a.zip <> b.zip)
) a ON a.ssan = c.ssn
WHERE c.print_old IS NULL
注意:我还将您的JOIN更改为显式的INNER JOIN。
答案 1 :(得分:0)
由于您引用了Lib1和Lib2,我假设您使用的是IBM中端系统,对吗?
我认为memno在table1中是唯一的,{memno,groupid,type,datec}在tableb中是唯一的。
SELECT a.memno,
a.name,
a.addr1,
a.addr2,
a.city,
a.state,
a.zip,
a.sex,
a.lname,
a.ssan,
b.addr1 as old_addr1,
b.addr2 as old_addr2,
b.city as old_city,
b.state as old_state,
b.zip as old_zip,
b.datec,
b.timec,
c.PRINT_OLD
c.PRINT_NEW
FROM Lib1.Table1 a
JOIN Lib1.Table2 b
ON a.memno = b.memno
and b.datec = 20131206
AND (a.addr1, a.addr2, a.city, a.state, a.zip)
<> (b.addr1, b.addr2, b.city, b.state, b.zip)
JOIN Lib1.TableC c
ON c.ssn = a.ssan
and c.datec = b.datec
and c.timec = b.timec
WHERE c.PRINT_OLD is NULL
and b.groupid = 'P2'
and b.type = 'B'
and b.datec = 20131206
我怀疑这与你正在寻找的更接近,并展示了一些不同的技巧。