Reputation: 6672
I have a products table with a stock field and a timestamp field that indicates the last time the product has been updated.
I need to write a query that pulls all the products that have stock>=0 and, for those that stock=0, to check if the difference between the timestamp and the current time is less than 30 days . If stock=0 and datediff(now(), timestamp)>30 then to exclude the products from the recordset.
So far I've written a query (see below) but it's incorrect as it will exclude even the products with stock>0 when they havent been updated in a the past 30 days.
select * from products where stock>=0 and datediff(now(), timestamp)>=30;
Upvotes: 2
Views: 74
Reputation: 308
SELECT * FROM products
WHERE
stock>0
OR (
stock=0
AND datediff(now(), timestamp)<=30
);
Upvotes: 1
Reputation: 6304
EDIT:
As per your comment, here is the answer very cryptic question
SELECT * FROM products WHERE stock > 0
OR (stock = 0 and DATEDIFF(NOW(), timestamp) <= 30);
Upvotes: 1
Reputation: 121922
Is it what you want?
SELECT * FROM products WHERE stock > 0 OR stock = 0 AND DATEDIFF(NOW(), timestamp) <= 30;
If stock
field is unsigned, the condition 'stock = 0' can be removed.
Upvotes: 2