开发者

SQL IF THEN for concatenating fields

I hav开发者_Python百科e two columns that are min_price and min_price. Most of the time, the min_price and max_price is the same. Instead of two separate fields for the price, I would like just one "price" field. If the min_price and the max_price are the same I want to display that price. If the min_price and max_price are different, then I would like to show a concatenated string that is (min_price "-" max_price). This is just for a table grid, so data types are not important.

Would I use an IF THEN statement in my select?

select (lots of other stuff), min_price, min_price, (lots more stuff)

Not sure where to go from here. I am using MySQL 5.


You can use the case statement like this:

Select case when min_price = max_price then
            min_price
        else
            concat(min_price, '-' , max_price)
        end AS Price
from some_table

See here for more info: http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html


Here you go:

select if(min_price=max_price,min_price,concat(min_price,' - ',max_price)) as price
from your_table;


SELECT CASE WHEN max_price = min_price then cast(min_price as varchar(31)) 
       ELSE cast(min_price as varchar(15) + '-' + cast(max_price as varchar(15) 
       END as Pricew
FROm Some_table
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜