sumit
sumit

Reputation: 11257

Using now() function in MySQL query

I am having a table with the following structure:

ITEMS ('id' int(10), 'stock' int(10), 'date_updated' DATETIME);

id is the primary key.

Some sample rows of my table are:

id  stock  date_updated
--  -----  -------------------
1   50     2011-11-05 05:00:00
2   40     2011-11-04 05:00:00
3   30     2011-11-03 05:00:00
4   20     2011-11-02 05:00:00

Suppose the time right now is: 2011-11-06 04:00:00

Problem: Find out the sum of all the stock which are having date_updated within last 2 days.

Example: If I run query now, then it should output 90 i.e. 50+40 -- the sum of rows with id = 1 and id = 2 as these rows having date_updated column within last 2 days.

I am trying the following query but no success. Please help!

SELECT sum(stock)
FROM items
WHERE date_updated > now() - 2;

I am using PHP, MySQL, Apache on Windows machine.

Upvotes: 2

Views: 3270

Answers (1)

Mark Byers
Mark Byers

Reputation: 838226

Use INTERVAL:

SELECT SUM(stock)
FROM items
WHERE date_updated > NOW() - INTERVAL 2 DAY

Upvotes: 5

Related Questions