2011-01-11 57 views
1

選擇不同/聯合我有兩個表:如何從兩個表

Table 1 

    id date 
    1 01-JAN-2011 
    2 01-JAN-2011  
    3 01-JAN-2011 

Table 2 

    id index 
    1  01 
    1  05 
    1  06 
    2  01 
    2  02 
    3  01 
    3  07 

我想一次列出所有的ID號碼,其中沒有索引號06或07的該ID的任何條目。所以在這種情況下,例如,我應該只獲得id 2。表1我需要使用日期搜索。

回答

3
SELECT DISTINCT id 
    FROM table2 t 
WHERE NOT EXISTS (SELECT NULL 
        FROM table2 
        WHERE t.id = id 
         AND index IN ('06', '07')) 
0

名義上,表1是無形的給你指定的條件:

SELECT DISTINCT t2.id 
    FROM Table2 AS t2 
WHERE t2.id NOT IN (SELECT DISTINCT t2a.id 
         FROM Tble2 AS t2a 
         WHERE t2a.index IN('06', '07') 
        ); 

但是,如果只想項,表1中也匹配的ID,那麼:

SELECT DISTINCT t1.id 
    FROM Table1 AS t1 
    JOIN (SELECT DISTINCT t2.id 
      FROM Table2 AS t2 
     WHERE t2.id NOT IN (SELECT DISTINCT t2a.id 
           FROM Tble2 AS t2a 
           WHERE t2a.index IN('06', '07') 
          ) 
     ) AS t3 
    ON t1.id = t3.id; 

請注意,我將索引編碼爲字符串'06','07',因爲如果索引實際上是數字列,則前導零不重要。如果您的Table.Index列實際上是一些數字類型,請刪除引號和前導零;它甚至可以爲你提供(稍微)更好的性能。

1

通常最好發佈實際的表定義/插入語句,以便人們可以針對他們編寫和測試他們的解決方案。這是我嘗試使用下面的示例表:

select ID from T2 
except 
select ID from T2 where Indx in ('06','07') 

這在SQL Server中測試2008

示例表:

create table T2 (
    ID int not null, 
    Indx char(2) not null 
) 
go 
insert into T2(ID,Indx) 
select 1,'01' union all 
select 1,'05' union all 
select 1,'06' union all 
select 2,'01' union all 
select 2,'02' union all 
select 3,'01' union all 
select 3,'07' 
go