0

How to using IF statement in WHERE? Below code doesn't works

SELECT item.item_id, 
       item.item_name, 
       item.item_qty 
IF(sell.product_qty IS NULL, item.item_qty, item.item_qty - SUM(sell.product_qty)),
       sell.date_order, 
       sell.date_shipping
FROM item
     OUTER JOIN sell
                ON item.item_id = sell.product_item_id
WHERE NOW() BETWEEN sell.date_order AND sell.date_shipping
HaveNoDisplayName
  • 8,291
  • 106
  • 37
  • 47
  • 2
    What do you mean by doesn't work? Are you getting an error? What results are you expecting and what results are you getting? – Tot Zam Jan 19 '16 at 04:08
  • Not exactly sure what you are asking, but this link might help: http://stackoverflow.com/questions/63447/how-to-perform-an-if-then-in-an-sql-select – Tot Zam Jan 19 '16 at 04:16
  • Please check [http://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html](http://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html) for an idea on IF – Quicksilver Jan 19 '16 at 04:40
  • @Tot Zam: Error Msg: "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near " – Juniantoじゅにあんと Jan 19 '16 at 05:58

1 Answers1

0

You should use CASE statement.

CASE WHEN sell.product_qty IS NULL THEN item.item_qty 
ELSE item.item_qty - SUM(sell.product_qty) END
Dr. Stitch
  • 908
  • 6
  • 15