[英]SQL - selecting rows with date and time conditions
我正在嘗試選擇小於或等於今天日期的所有行(這部分正在工作),但我不想要今天 $time 小於結束時間的行。
測試表:{ID,日期,狀態,checkid}
檢查表:{checkid, startt, endt}:開始和結束是如下所示的時間值。
$time = '15:00:00';
$query = ("SELECT test.ID, test.status, check.startt, check.endt FROM test INNER JOIN check ON test.checkid=check.checkid
WHERE test.date <='$date' AND $time < check.endt");
如果時間小於檢查表中的結束時間,則查詢不會顯示任何內容。 我知道我做錯了什么,但我無法弄清楚,我正在嘗試一個 if 語句 atm。
基本上編碼你所描述的......即test.date
= "today" 時的特殊處理
日期上的條件“1”始終適用(但不包括今天)
條件“2”涉及日期和時間(今天)。
WHERE test.date < $date
OR (test.date = $date AND check.endt <= $time)
注意:請注意,如果您嘗試組合日期和時間,以便執行單個比較:這是可能的; 但查詢將無法利用索引,因此不可取。
PS:您的要求有更直接的翻譯。 不幸的是,它有點冗長,優化器可能無法找到最佳計划。
where test.date <= $date
and test.id not in (
select test.id
from ...
where test.date = $date
and check.endt > $time
)
也適用於支持EXCEPT
子句的平台(顯然很多流行的 EXCEPT mysql 除外):
select Col1, Col2
from ...
where test.date <= $date
except
select Col1, Col2
from ...
where test.date = $date and check.endt > $time
EXCEPT
語法讀起來非常自然,盡管它非常冗長。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.