Reputation: 13651
I'm having trouble with a SQL query, I can't think how to phrase it.
It's to pull a count of events from a log since you last checked it.
Currently I have this:
SELECT COUNT(*) AS alertcount, date AS alertdate
FROM alerts WHERE to_id = '$id' AND date > '$lastcheck'
But, I want it to exclude all fields where expire=1
and the date
is over 30 mins old.
So if both of them expressions are true, it will ignore that record in the count.
Upvotes: 2
Views: 267
Reputation: 36146
SELECT COUNT(*) AS alertcount, date AS alertdate
FROM alerts
WHERE to_id = '$id' AND (date between '$lastcheck' and getdate() -30 minutes ) and expire!=1
I dont know your DB engine but if is SQL Server, use the dateadd
function to calculate the getdate() -30 minutes
expression
EDIT: here is the condition with your new comment. not sure where the to_id will fit in this scenario and also you dont need a date parameter
WHERE ((expire=0) OR (date > getdate() -30 minutes and expire=1) )
Upvotes: 1
Reputation: 26737
SELECT COUNT(*) AS alertcount, date AS alertdate
FROM alerts WHERE to_id = '$id' AND date > '$lastcheck'
AND(expire<>1 AND DateDiff(MINUTE, [date] , GETDATE())>30)
Upvotes: 0
Reputation: 79929
I think you are looking for HAVING
, something like:
SELECT COUNT(*) AS alertcount, date AS alertdate
FROM alerts
WHERE to_id = '$id' AND date > '$lastcheck'
HAVING expire = 1 and DATEADD(minute, -30, GETDATE()) < yourDateField
Upvotes: 0
Reputation: 726579
This should work (I am using SQL Server date-time functions)
SELECT
COUNT(*) AS alertcount
, date AS alertdate
FROM alerts
WHERE to_id = '$id' AND date > '$lastcheck'
AND (expire <> 1 OR dateadd(minute, -30, getdate()) < date)
Upvotes: 1