10

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

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 附近的语法错误。

4

5 回答 5

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;

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

于 2013-09-06T15:41:20.007 回答
2

那是完全错误的case语法。如果您所做的只是更改这些字段的别名,那么请在您的客户端中进行转换。

例如

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..
}
于 2013-09-06T15:40:13.193 回答
1

更改字段选择的顺序,因为 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;
于 2017-11-03T11:06:04.187 回答
0

You are close, it looks like this

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;
于 2013-09-06T15:42:36.740 回答
0

我不知道什么是field_XXXX内容,

但是我可以通过重用查询中的开关盒来使它工作,就像这样:(我在这里使用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; 

也许这就是你的意思。

于 2017-07-19T07:54:20.640 回答