Reputation: 43
Is it possible to do an mysql if/then statement with math?
Say...
if product_name = "apple"
then divide product_price by 4
else do no math on product_price
Link to a tutorial on something like this or any help/direction would be appreciated.
I ended using bluefeet's method and up with this. Sample for anyone else that may need in the future,
SELECT DISTINCT
12345_parts.*,
12345_parts.install_meter +
12345_parts.meter_life -
12345_parts.prior_meter
AS nextdue,
CASE
WHEN 12345_parts.part_name = "JET ENGINE"
THEN 12345_parts.meter_life + 12345_parts.install_meter - 12345_parts.prior_meter - status_12345.meter / 4
ELSE 12345_parts.meter_life + 12345_parts.install_meter - 12345_parts.prior_meter - status_12345.meter
END AS remainder
FROM 12345_parts, status_12345
WHERE 12345_parts.overhaul LIKE '%HLY%'
AND 12345_parts.active='ACTIVE'
Upvotes: 4
Views: 1440
Reputation: 247840
You can also use a CASE
statement:
select
case
when product_name = 'apple'
then product_price/4
else product_price
end as price
from yourtable
Upvotes: 1
Reputation: 29051
Try this:
SELECT IF(product_name = "apple", product_price / 4, product_price) price
FROM products;
Upvotes: 4
Reputation: 425
From your example, you can just do:
IF (product_name = "apple")
BEGIN
SELECT product_name, (product_price/4)
FROM table
END
Upvotes: 1
Reputation: 16086
You can try this-
select If(product_name = "apple",product_price/4,product_price) as cal from tableName
Upvotes: 0