mysql选择case多列为

时间:2013-09-06 15:34:43

标签: mysql

我想用这样的东西设置多个字段,我怎样才能使它工作?

Select TableId,
    CASE
        WHEN StartTime > Appt THEN
            Field AS Field_1
            FieldId AS FieldId_1
        WHEN StartTime BETWEEN Appt AND DATE_ADD(Appt, INTERVAL 1 MONTH) THEN
            Field AS Field_2
            FieldId AS FieldId_2
    END
FROM TableA;

它不起作用,AS Field_1附近的语法错误。

5 个答案:

答案 0 :(得分:6)

您尝试在SQL语句中执行类似于宏扩展的操作,但您无法执行此操作。解决问题的最简单方法是在应用程序代码中动态编写SQL,并从应用程序中有条件地执行该语句。

如果必须在SQL中执行此操作,则可以选择几种方法。

每个CASE都是一个表达式,因此您只能通过为每列单独CASE单独生成输出字段:

SELECT ID,
  CASE WHEN StartTime > Appt THEN Field_A 
       WHEN StartTime BETWEEN Appt AND DATE_ADD(Appt, INTERVAL 1 MONTH) THEN
        Field_B
  END AS field1,
  CASE WHEN StartTime > Appt THEN Field_C 
       WHEN StartTime BETWEEN Appt AND DATE_ADD(Appt, INTERVAL 1 MONTH) THEN
        Field_D
  END AS field2
FROM TableA;

或者,在存储过程中使用statement form of CASE(或IF(可能更简单),包含语句的多个版本并有条件地执行它们。

答案 1 :(得分:2)

完全破坏了case语法。如果你正在做的只是更改这些字段的别名,那么在你的客户端进行转换。

e.g。

SELECT (StartTime > Appt) AS case1,
       (StartTime BETWEEN Appt AND Appt + INTERVAL 1 MONTH) AS case2
       Field,
       FieldID
FROM TableA

if ($row['case1']) then
    $field_1 = $row['Field'];
    $fieldid_1 = $row['FieldID'];
} else if ($row['case2']) {
    etc..
}

答案 2 :(得分:0)

你很接近,看起来像这样

Select TableId,
    CASE WHEN StartTime > Appt THEN Field   ELSE NULL END AS Field_1,
    CASE WHEN StartTime > Appt THEN FieldId ELSE NULL END AS FieldId_1,
    CASE WHEN StartTime BETWEEN Appt AND DATE_ADD(Appt, INTERVAL 1 MONTH) THEN Field ELSE NULL END AS Field_2 ,
    CASE WHEN StartTime BETWEEN Appt AND DATE_ADD(Appt, INTERVAL 1 MONTH) THEN FieldId ELSE NULL END AS FieldId_2

FROM TableA;

答案 3 :(得分:0)

我不知道field_XXXX内容是什么,

但我可以通过重用这个查询中的switch case来实现它: (我在这里使用temporary variable

SELECT TableId,
    CASE
        WHEN StartTime > Appt THEN
            @temp := 'Field_1' 
        WHEN StartTime BETWEEN Appt AND DATE_ADD(Appt, INTERVAL 1 MONTH) THEN
            @temp := 'Field_2' 
    END AS `Field`,
    CASE
        WHEN @temp := 'Field_1' THEN 'FieldId_1'
        WHEN @temp := 'Field_2' THEN 'FieldId_2'
    END AS `FieldId`
FROM TableA; 

也许这就是你的意思。

答案 4 :(得分:0)

更改字段选择的顺序, 因为case应该是第一个用mysql中的别名检索的列 代码应如下

Select 
    CASE
        WHEN StartTime > Appt THEN
            Field AS Field_1
            FieldId AS FieldId_1
        WHEN StartTime BETWEEN Appt AND DATE_ADD(Appt, INTERVAL 1 MONTH) THEN
            Field AS Field_2
            FieldId AS FieldId_2
    END as <alias>,
TableId
FROM TableA;