2016-10-25 2 views
0

나는 이런 식으로 내 테이블 StartDateEndDate에 있습니다테스트 경우

+----+----------------------+--------------------+ 
| id | start_date   | end_date   | 
+----+----------------------+--------------------+ 
| 1 | 2016-10-24 09:00:00 |2016-10-24 10:30:00 | 
| 2 | 2016-10-31 09:00:00 |2016-10-31 10:30:00 | 
+----+----------------------+--------------------+ 

내가 테스트 할 경우 내 새로운 기록 (new start_dateend_date) 하지 참여 ONE SECONDE 다른 레코드들.

select * from myTable where 

(new_start_date >= myTable.start_date and new_end_date <= myTable.end_date) 

or (new_start_date > myTable.start_date and new_end_date < myTable.end_date) 

or (new_start_date > myTable.start_date and new_end_date < myTable.end_date) 

or (new_start_date < myTable.start_date and new_end_date > myTable.end_date) 

or (new_start_date < myTable.start_date and new_end_date = myTable.end_date) 

or (new_start_date = myTable.start_date and new_end_date > myTable.end_date) 

인가 :

내가 모든 가능성을 테스트하는 데 사용,하지만 난이이 문제에 대한 좋은 해결책이 시간이 오래 걸릴 생각, 내가 그것을 잘 작동하지만, 시간을이 쿼리에 tryed 이 문제에 대한 다른 해결책이 있습니까?
newSD_______startdate___newED_____enddate_____ : return false 

newSD_______startdate________enddate___newED__ : return false 

___startdate___newSD____newED_____enddate_____ : return false 

___startdate___newSD_____enddate___newED______ : return false 

____startdate_____enddate___newED___newED_________ : return true 

___newED___newED___startdate_____enddate__________ : return true 

감사합니다 : 여기

경우 내가 얻을 수있는 모든 가능성이다.

+0

MySQL 또는 PostgreSQL? – Barmar

+1

참조 http://stackoverflow.com/questions/6571538/checking-a-table-for-time-overlap – Barmar

+0

미안 해요 postgreSQL –

답변

3

문자 그대로 의미 간격.

select * 
from myTable 
where (new_start_date, new_end_date) overlaps (start_date, end_date); 

위의 내용은 ANSI 표준 SQL입니다.


원하는 경우 겹치는 행을 삽입하지 못하게하는 제약 조건을 만들 수 있습니다.

이것은 range type을 통해 exclusion constraint으로 이루어집니다. 이는 일종의 고유 제한 조건이지만 범위에 대한 것입니다.

alter table mytable 
    add constraint no_overlap 
    exclude using gist (tsrange(start_date, end_date) with &&); 

제외 조건은 Postgres에 따라 다릅니다.

+0

나는 이것이 @a_horse_with_no_name에 도움이 될 것을 본다, 대단히 감사한다. –

2

너무 복잡합니다. 훑어 봐 : "X"와 "Y"는 "a는"와 "B"데이터베이스 값입니다 테스트하는 데 필요한 값이 있으며, 경우에, 여기 모두 배치하는 방법은 다음과 같습니다

  a b 
1  x y   - x<a & y<a - no overlap 
2  x y   - x<a & y=a 
3  x  y  - x<a & a <= y <= b 
4  x  y  - x<a & y=b 
5  x   Y - x<a & y>b - complete overlap 
6   x y  - x=a & y<b 
7   x y  - x=a & y=b - same dates 
8   x  y - x=a & y>b 
9   xy  - (x>a & x<b) & (y>a & y<b) - complete overlap 
10    x y  - (x>a & x<b) & b=y 
11    x y - x=b & y>b 
12    x y - x>a & y>a - no overlap 
모든 이들의 아웃

, 당신은 약 112 치료 - 아니 중복을 전혀 논리 문이 당신에게 새로운 시작/끝과 겹쳐있는 모든 행을 표시합니다 단지

if ((y < a) || (x > b)) { 
    ... no overlap 
} 
+0

감사합니다 @ MarcB 그래서 내 쿼리를 사용할 수 있습니까? 또는 다른 최소화 된 방법이 있습니까? 아니면 더 빨리? –

+0

은 가능한 한 최소 수준입니다. 'x

+0

다른 방법이 없으므로 지금까지 내 솔루션이 사실입니까? –

관련 문제