使用SQL Server 2000
Database1.Table1
ID Name Date title
001 Ravi 23-02-2009 Accountant
001 Ravi 24-02-2009 Accountant
001 Ravi 25-02-2009 Accountant
002 Ram 21-02-2009 Supervisors
002 Ram 25-02-2009 Supervisors
002 Ram 26-02-2009 Supervisors
所以......,
Database2.Table2
ID Name Date1 Date2
001 Ravi 23-02-2009 24-02-2009
002 Ram 21-02-2009 24-02-2009
所以......
假设我要显示从21-02-2009到26-02-2009的记录 - 预期产出:
001 Ravi 25-02-2009 Accountant
002 Ram 25-02-2009 Supervisors
002 Ram 26-02-2009 Supervisors
从上面两个表中我想显示来自Database1.table1的id,name,date,title,其中Database1.table1.id不应该在database2.table2的date1和date2之间显示:
(23-02-2009 to 24-02-2009) ID should not display from table1
(21-02-2009 24-02-2009) ID should not display from table1
如何在SQL中进行查询?
任何人都可以帮助我。
答案 0 :(得分:1)
对于Table1中的每一行,我们在Table2中查找行,并仅显示没有Table2匹配的行:
SELECT
TABLE1.*
FROM TABLE1
LEFT JOIN TABLE2
ON
(TABLE1.ID = TABLE2.ID) AND --JOIN TABLE2 BY ID
(TABLE1.DATE BETWEEN TABLE2.DATE1 AND TABLE2.DATE2) --AND BY DATE CRITERIA
WHERE
(TABLE2.ID IS NULL) AND --SHOW ONLY IF IT DIDN'T MATCH ROW IN TABLE2
(TABLE1.DATE BETWEEN '21-02-2009' AND '26-02-2009')
SELECT
TABLE1.*
FROM TABLE1
LEFT JOIN TABLE2
ON
(TABLE1.ID = TABLE2.ID) AND --JOIN TABLE2 BY ID
(TABLE1.DATE BETWEEN TABLE2.DATE1 AND TABLE2.DATE2) --AND BY DATE CRITERIA
WHERE
(TABLE2.ID IS NULL) AND --SHOW ONLY IF IT DIDN'T MATCH ROW IN TABLE2
(TABLE1.DATE BETWEEN '21-02-2009' AND '26-02-2009')
答案 1 :(得分:1)
尝试:
SELECT t.id,
t.name,
t.date,
t.title
FROM TABLE_1 t
WHERE NOT EXIST(SELECT NULL
FROM TABLE_2 t2
WHERE t.date BETWEEN t2.date1 AND t2.date2)
如果您的数据模型将日期存储在字符串中,请更新NOT EXISTS以使用CAST / CONVERT将它们更改为DateTime ...
请注意LEFT JOIN/IS NULL is not as efficient as NOT IN/NOT EXISTS in SQL Server。
答案 2 :(得分:0)
我想你正在寻找这个:
select db1.id, db1.name, db1.date, db1.title
from database1.table1 as db1
join database2.table2 as db2 on db1.id = db2.id
where db1.date < db2.date1
or db1.date > db2.date2
-don