Mysql SQLselect中的用户变量if

时间:2015-01-23 05:51:25

标签: mysql variables if-statement

以下句子中的用户定义变量是非常有线的,

  SELECT   
           @f:=CONVERT(
             IF(@c<=>CatId  AND DATEDIFF(Date, @d)=1, @f, Date), DATE
           ) AS Begin,
           @c:=CatId, @d:=Date
  FROM     my_table  AS init
  ORDER BY CatId, Date

如此处所示:http://sqlfiddle.com/#!2/fddbd/83,my_table由:

给出
CREATE TABLE my_table (
  Id    INT(6) UNSIGNED ZEROFILL,
  CatId INT,
  Date  DATE,
  Rate  INT
);

INSERT INTO my_table
VALUES
  (000001, 12, '2009-07-07', 1),
  (000002, 12, '2009-07-08', 1),
  (000003, 12, '2009-07-09', 1),
  (000004, 12, '2009-07-10', 2),
  (000005, 12, '2009-07-15', 1),
  (000006, 12, '2009-07-16', 1),
  (000007, 13, '2009-07-08', 1),
  (000008, 13, '2009-07-09', 1),
  (000009, 14, '2009-07-07', 2),
  (000010, 14, '2009-07-08', 1),
  (000010, 14, '2009-07-10', 1);

更确切地说,变量@f没有预先定义,mysql将为DateDiff做什么逻辑?

1 个答案:

答案 0 :(得分:1)

在第一行,它将使用NULL作为所有变量的值。所以它等同于以下查询将所有显式初始化

SELECT   
    @f:=CONVERT(
        IF(@c<=>CatId  AND DATEDIFF(Date, @d)=1, @f, Date), DATE
    ) AS Begin,
    @c:=CatId, @d:=Date
FROM my_table  AS init
CROSS JOIN (SELECT @f := NULL, @c := NULL, @d := NULL) AS vars
ORDER BY CatId, Date

通常不建议将ORDER BY子句放在与处理相同的查询级别中。 MySQL执行此操作的方式不同,具体取决于ORDER BY子句中SELECT中的列是否已命名。如果是,则在生成所有结果后执行排序,否则在处理之前使用它来排序表中的行。获得可预测结果的方法是使用子查询:

SELECT   
    @f:=CONVERT(
        IF(@c<=>CatId  AND DATEDIFF(Date, @d)=1, @f, Date), DATE
    ) AS Begin,
    @c:=CatId, @d:=Date
FROM (SELECT *
      FROM my_table
      ORDER BY CatId, Date)  AS init
CROSS JOIN (SELECT @f := NULL, @c := NULL, @d := NULL) AS vars

由于您在不同的MySQL版本上看到不同的结果,这可能还取决于版本。使用子查询应该使其一致地工作。