bikey77
bikey77

Reputation: 6672

MySQL, a little help with conditions

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

Answers (3)

sw0x2A
sw0x2A

Reputation: 308

SELECT * FROM products 
WHERE 
        stock>0 
OR (
        stock=0
        AND datediff(now(), timestamp)<=30
);

Upvotes: 1

bash-
bash-

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

Devart
Devart

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

Related Questions