2012-10-04 211 views
1

我有兩個表,table1table2。他們都有相同的列,program_id,scheduled_timetimezone_idSQL - 比較兩個表

我想檢索具有相同的program_idtimezone_id但與table1不同的scheduled_time的行。

所以這裏是我試過SQL:

select t1.* 
from table1 t1, table2 t2 
where t1.program_id = t2.program_id 
    and t1.timezone_id = t2.timezone_id 
    and t1.scheduled_time != t2.scheduled_time; 

但我仍然看到有相同program_idscheduled_timetimezone_id行。

有人能解決這個SQL?

謝謝。

+2

您正在使用什麼數據庫管理系統? –

+3

這真的是你嘗試過的SQL嗎?因爲它似乎永遠不會定義't1'。 。 。 – ruakh

+5

看到(和** **擁抱!)[壞習慣踢:使用舊樣式的JOIN(http://sqlblog.com/blogs/aaron_bertrand/archive/2009/10/08/bad-habits-to- )使用老的風格,joins.aspx踢 - 使用** **正確的ANSI/ISO JOIN語法 –

回答

2

嘗試是這樣的:

SELECT 
    t1.* 
FROM 
    table1 t1 
INNER JOIN 
    table2 t2 ON t1.program_id = t2.program_id AND t1.timezone_id = t2.timezone_id 
WHERE 
    t1.scheduled_time <> t2.scheduled_time 

基本上,做共同列的INNER JOINprogram_idtimezone_id),並確保scheduled_time列有一個不同的價值。

另外:在SQL使用<>運營商 - !=是C#/ VB.NET ....

+0

我仍然可以看到與查詢具有相同的program_id,scheduled_time和timezone_id的行。在這一點上,我有點困惑。 – user826323

2

嘗試使用子查詢:

select t1.* 
from table1 t1 
where exists 
(
    select 1 
    from table2 t2 
    where t1.program_id = t2.program_id 
    and t1.timezone_id = t2.timezone_id 
    and t1.scheduled_time != t2.scheduled_time; 
) 
0

這應該工作。我會建議總是指定一個列列表,而不是使用SELECT *

SELECT t1.program_id, t1.scheduled_time, t1.timezone_id 
FROM table1 t1 
INNER JOIN table2 t2 ON 
    t2.program_id = t1.program_id AND 
    t2.timezone_id = t1.timezone_id 
WHERE 
    t2.scheduled_time <> t1.scheduled_time