sql列格式化

时间:2013-02-08 15:36:35

标签: mysql sql formatting

问一个简单的问题

在MySQL中,我如何将数值显示为字符串等值?

所以

1 = New
2 = Old
3 = Cancelled

所以,如果我有点像

SELECT object_name, object_status where object_status > 0

并且返回了

object#1, 1
object#2, 2
object#3, 1
object#4, 3

但我想要它显示

object#1, New
object#2, Old
object#3, New
object#4, Cancelled

先谢谢KS

3 个答案:

答案 0 :(得分:4)

你可以使用CASE

SELECT object_name,         
        CASE object_status 
            WHEN 1 THEN 'New'
            WHEN 2 THEN 'Old'
            WHEN 3 THEN 'Cancelled'
            ELSE NULL
        END status
where object_status > 0

SELECT object_name,         
        CASE 
            WHEN object_status = 1 THEN 'New'
            WHEN object_status = 2 THEN 'Old'
            WHEN object_status = 3 THEN 'Cancelled'
            ELSE NULL
        END status
where object_status > 0

答案 1 :(得分:2)

SELECT object_name, 
 case object_status when 1 then 'New' 
  when 2 then 'Old' 
  when 3 then 'Cancelled' end as status
from myTable
where object_status > 0

答案 2 :(得分:2)

您可以创建一个新的映射表并将两个表连接在一起。新表将有2列 - object_status列和漂亮名称列。然后加入两个。

SELECT s.object_name, sm.StatusName
FROM Status s
INNER JOIN StatusMapping sm on s.object_status = sm.object_status
WHERE s.object_status > 0

这将允许您根据需要添加新映射,而无需更改查询。