mysql获取相反结果,如何使用BETWEEN在MySQL查询中相反?

I have a working query which used "BETWEEN" to find results within a date range, what i need is just opposite result or not between the given date range. Here is the query below.

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

Can anyone help me finding opposite result or result of not between the date range having the same conditions?

解决方案

The only thing I can think of is that, somehow, the expressions that define the date interval are returning a time section (those strtotime() look like the culprits). This answer deals with two options (option 2 is the good one) when the date includes a time part.

In your specific case, I think this would be the best approach to solve the issue:

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

Notice that the date() function "removes" the time section of the value.

One more thing: Your code may be vulnerable to SQL Injection attacks. Please take a look here for a (humorous) example on what it is, and tips on how to deal with it.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>