2011-05-13 60 views
0

我有兩個表的結構是這樣的:需要使用SQL查詢幫助

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

你能用文字描述你試圖用你的查詢來達到什麼目的嗎? – 2011-05-13 18:36:03

+0

我正在試圖合併表格, – NULL 2011-05-13 18:42:16

+0

請問您可以告訴我們,**您正在使用的數據庫,版本和版本? – 2011-05-13 18:42:25

回答

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 
0

你可能想要的ID:■是唯一的。將主鍵添加到ID列。

+0

一個人發佈了一個他正確的解決方案,這是兩個左連接。不是一個內在的聯結,像魅力一樣工作,謝謝反正。 – NULL 2011-05-13 19:10:43