2014-09-24 44 views
1

我有一個工作查詢,它​​使用「BETWEEN」在日期範圍內查找結果,我需要的僅僅是給定日期範圍之間的結果或相反結果。以下是下面的查詢。如何在MySQL查詢中使用BETWEEN的對立方式?

SELECT loanac.id, loanac.name, loanac.lacc, loanac.phone, 
SUM(loantrans.in) as totalin, SUM(loantrans.out) as totalout 

FROM loanac, loantrans 
WHERE (loanac.lacc=loantrans.account) 
AND (`loantrans`.`date` BETWEEN CAST('$range' AS DATE) AND CAST('$date' AS DATE)) 

GROUP BY loanac.lacc 
HAVING SUM(IFNULL(`loantrans`.`out`,0)) > SUM(IFNULL(`loantrans`.`in`,0)) 

任何人都可以幫助我找到相反的結果或不具有相同條件的日期範圍之間的結果嗎?

詳細截圖在這裏:https://www.dropbox.com/sh/lgmop3zxqaf9mjy/AAAWVWjZXd8da9KDDOqz2ANla?dl=0

回答

1

我能想到的唯一的事情是,不知何故,限定日期間隔的表達式返回一個時間段(那些strtotime()樣子的罪魁禍首)。當日期包括時間部分時,This answer涉及兩個選項(選項2是好的選項)。

在特定情況下,我認爲這將是解決問題的最佳途徑:

SELECT loanac.id, loanac.name, loanac.lacc, loanac.phone 
    , SUM(loantrans.in) as totalin, SUM(loantrans.out) as totalout 
FROM loanac 
    INNER JOIN loantrans on loanac.lacc = loantrans.account 
-- Instead of an implicit join in the WHERE clause, use an explicit INNER JOIN 
WHERE date(loantrans.date) < date('$range') 
    AND date(loantrans.date) > date('$date') 
GROUP BY loanac.lacc 
HAVING SUM(IFNULL(`loantrans`.`out`,0)) > SUM(IFNULL(`loantrans`.`in`,0)) 

注意,date()功能「刪除」的值的時間段。


一兩件事:你的代碼可能會受到SQL注入攻擊。請致電take a look here瞭解一下(幽默)例子,以及如何處理它的提示。

0

鑑於您的$ date和$ range僅僅是「now」和「6 days ago」,因此有NO原因是要在PHP中生成日期。爲什麼不乾脆

WHERE datefield BETWEEN (curdate() - INTERVAL 6 DAY) AND curdate() 
a.k.a. 
WHERE datefield BETWEEN '2014-09-19' AND '2014-09-25' 
a.k.a 
WHERE (datefield >= '2014-09-19') AND (datefield <= '2014-09-25') 

爲其相反(NOT)將

WHERE (datefield > curdate()) OR (datefield < (curdate() - INTERVAL 6 DAY)) 
a.k.a 
WHERE (datefield > '2014-09-25') OR (datefield < '2014-09-19') 
+0

對不起,沒有工作,這裏是在細節https://www.dropbox.com/sh/lgmop3zxqaf9mjy/截圖AAAWVWjZXd8da9KDDOqz2ANla?dl = 0 – Machine 2014-09-27 08:54:42

+0

該圖完全沒有幫助。你顯示lacc 975,976和loantrans 1010的記錄。這兩個片段根本不相關。 – 2014-09-29 14:48:34