用于检查null的select语句中的MYSQL Case

时间:2012-11-12 07:06:17

标签: mysql sql

如果我通过,则在MySQL查询中

  case guides.Gud_Publish_Date 
     when null then "Unscheduled" 
     else "Forth Coming Titles" 
  end

然后它认为即使Gud_Publish_Date也有值,所有都为null。完整的SQL语句是

SELECT guides.Gud_Id
    , guides.Gud_Image
    , guides.Gud_SubEditor
    , guides.Gud_Reprint_Status
    , guides.Gud_Publish_Date
    , guides.Gud_Img_Chk
    , guides.Gud_Published
    , guides.Gud_View
    , (
        CASE guides.Gud_Publish_Date
            WHEN NULL
                THEN "Unscheduled"
            ELSE "Forth Coming Titles"
            END
        ) AS Schedules
FROM guides

任何人都可以帮助我吗?提前致谢

4 个答案:

答案 0 :(得分:53)

尝试使用IF

SELECT guides.Gud_Id
    , guides.Gud_Image
    , guides.Gud_SubEditor
    , guides.Gud_Reprint_Status
    , guides.Gud_Publish_Date
    , guides.Gud_Img_Chk
    , guides.Gud_Published
    , guides.Gud_View
    , IF(guides.Gud_Publish_Date IS NULL,'Unscheduled','Forth Coming Titles') 
             AS Schedules
FROM guides

或者如果你真的想要CASE

SELECT guides.Gud_Id
    , guides.Gud_Image
    , guides.Gud_SubEditor
    , guides.Gud_Reprint_Status
    , guides.Gud_Publish_Date
    , guides.Gud_Img_Chk
    , guides.Gud_Published
    , guides.Gud_View
    , (
        CASE 
            WHEN guides.Gud_Publish_Date IS NULL
            THEN 'Unscheduled'
            ELSE 'Forth Coming Titles'
        END
      ) AS Schedules
FROM guides

答案 1 :(得分:10)

我发现了这个 - 几个月的帖子。使用Rajan预期的COALESCE选项,您可以这样做,

SELECT guides.Gud_Id
    , guides.Gud_Image
    , guides.Gud_SubEditor
    , guides.Gud_Reprint_Status
    , guides.Gud_Publish_Date
    , guides.Gud_Img_Chk
    , guides.Gud_Published
    , guides.Gud_View
    , CASE COALESCE(guides.Gud_Publish_Date, 0)
          WHEN 0 THEN 'Unscheduled'
                 ELSE 'Forth Coming Titles'
          END  AS Schedules
FROM guides

上面的代码假设guides.Gud_Publish_Date不能取值0,我可以这样做,因为它是一个日期。如果不是这种情况,您可以将0改为另一个不能取的值;也许你最喜欢的浮点数如3.1415或空标识符'null'

答案 2 :(得分:3)

SELECT guides.Gud_Id
    , guides.Gud_Image
    , guides.Gud_SubEditor
    , guides.Gud_Reprint_Status
    , guides.Gud_Publish_Date
    , guides.Gud_Img_Chk
    , guides.Gud_Published
    , guides.Gud_View
    , (
        CASE WHEN guides.Gud_Publish_Date IS NULL
            THEN "Unscheduled"
            ELSE "Forth Coming Titles"
            END
        ) AS Schedules
FROM guides

答案 3 :(得分:-2)

试试这个

SELECT guides.Gud_Id
    , guides.Gud_Image
    , guides.Gud_SubEditor
    , guides.Gud_Reprint_Status
    , guides.Gud_Publish_Date
    , guides.Gud_Img_Chk
    , guides.Gud_Published
    , guides.Gud_View
    , coalesce((
        CASE guides.Gud_Publish_Date
            WHEN NULL
                THEN 'Unscheduled'
            ELSE 'Forth Coming Titles'
            END
        ), 'Unscheduled') AS Schedules
FROM guides