2016-10-25 19 views
0

を参加しない場合:テスト二つの日付の間隔が他の間隔

+----+----------------------+--------------------+ 
| 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) 

ですこの問題の解決方法はありますか?

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

申し訳ありませんが、私はそのような私のクエリを使用することができます@ MarcBありがとう –

答えて

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

ありがとう?または別の最小化された方法がありますか?それとももっと速い? –

+0

それはあなたが得ることができる程度の最小限です。 'x

+0

他の方法はありません。私の解決策は今までは本当ですか? –

関連する問題