我有两个像这样的结构表:
表a
id title date
1 testing1 2001-05
1 testing2 2003-05
表格b
id code date
1 aaaa 2001-01
1 bbbb 2003-01
当我加入这两个表时,我得到三行,但我只想要2?
(query)
select distinct a.*, b.*
from table a, table b
where a.date in ('2001-05','2003-05')
and a.id=b.id
and b.date < a.date ---> I know the error is coming from here.
错误的输出看起来像这样
id title date id code date
1 testing1 2001-05 1 aaaa 2001-01
1 testing1 2003-05 1 aaaa 2003-01-------this is duplicated because the date is in fact less than,
1 testing2 2003-05 1 bbbb 2003-01
正确的输出应该是:
id title date id code date
1 testing1 2001-05 1 aaaa 2001-01
1 testing2 2003-05 1 bbbb 2003-01
答案 0 :(得分:0)
您可能希望ID:s是唯一的。将主键添加到ID列。
答案 1 :(得分:0)
Select A.id, A.title, A.date
, B.id, B.code, B.date
From TableA As A
Join (
Select A.id, A.title, A.date
, Min( B.Date ) As BDate
From TableA As A
Left Join TableB As B
On B.id = A.id
And B.Date < A.Date
Where A.Date In('2001-05-01','2003-05-01')
Group By A.id, A.title, A.date
) As Z
On Z.id = A.id
And Z.title = A.title
And Z.date = A.date
Join TableB As B
On B.id = A.id
And B.date = Z.BDate