开发者

Handling IF condtions in MySQL

I hav开发者_C百科e a query that based on various ids within a table should return different results.. So for example:

Table 'orders'

  • product_id
  • item_id
  • extra_id
  • something_id

I'd like return a result based on the values of these, such as

IF item_id != 0 'ITEM' ELESEIF product_id != 0 'PRODUCT', etc.

Does anyone know how to do this?

Thanks!


The CASE expression is ANSI, supported on numerous databases:

SELECT CASE 
         WHEN o.item_id != 0 THEN 'ITEM'
         WHEN o.product_id != 0 THEN 'PRODUCT'
       END AS your_column_name
  FROM ORDERS o

ANSI is preferred for the portability, rather than native vendor syntax where possible.


SELECT IF (item_id <> 0,'ITEM',IF (product_id <> 0, 'PRODUCT','N/A')) as type

http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜