防止SQL查询中的冗余结果

时间:2015-02-18 19:30:29

标签: sql

我查找时间冲突的查询是这样的 -

create table dat(id int, s time(7), e time(7));

insert into dat (id,s,e) values(1,'16:00:00.0000000','18:00:00.0000000')
insert into dat (id,s,e) values(2,'15:00:00.0000000','17:00:00.0000000')
insert into dat (id,s,e) values(3,'12:00:00.0000000','15:00:00.0000000')

//data part

QUERY - 

select * from dat a, dat b

 where  a.id != b.id 

and a.s < b.e and a.e > b.s

结果 - enter image description here

现在的问题是查询列表 -  在第一行中,id 1与id 2冲突

在第二行中,id 2与id 1冲突。

我需要这个查询的独特之处。请建议。

1 个答案:

答案 0 :(得分:2)

尝试:

SELECT * from dat a, dat b 
WHERE a.id < b.id 
    AND a.s < b.e 
    AND a.e > b.s

您可以通过将第一个ID设置为低于第二个ID来避免重复对。