声明的变量在select语句中重置

时间:2019-09-25 06:34:23

标签: mysql h2

我正在尝试重新创建从mysql到h2数据库的查询,但结果不一致。

查询

SELECT
    enrolmentid,
    @prev,
    questionid,
    @thisrow:= (
        CASE WHEN @prev = enrolmentid THEN
            @thisrow
        ELSE
            0
        END) + 1 AS row_num,
    @prev:= enrolmentid
FROM
    response,
    (SELECT @thisrow:= 0, @prev:= NULL) r
WHERE
    enrolmentid = 18620674
ORDER BY
    enrolmentid,
    questionid

表结构

CREATE TABLE `enrolment` (
  `enrolmentid` bigint(20) NOT NULL,
  `batch_reference` varchar(128) DEFAULT NULL,
  `destination` varchar(255) DEFAULT NULL,
  `enrolment_date` datetime DEFAULT NULL,
  `enrolment_reference` varchar(128) DEFAULT NULL,
  `response_report_id` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`enrolmentid`),
  KEY `FK9ueb1l045x7ignakryx64deir` (`response_report_id`)
);

使用MySQL的row_num正确递增:

enrolmentid,@prev,questionid,row_num,@prev:= enrolmentid
18620674,NULL,33909,1,18620674
18620674,18620674,33910,2,18620674
18620674,18620674,33911,3,18620674

但是H2似乎重置了每一行的变量

ENROLMENTID,@PREV,QUESTIONID,ROW_NUM,"SET(@PREV, ENROLMENTID)"
18620674,NULL,33909,1,18620674
18620674,NULL,33910,1,18620674
18620674,NULL,33911,1,18620674

有人知道在MySQL和H2之间实现这一目标的一致方法吗?提前非常感谢

1 个答案:

答案 0 :(得分:0)

在选择列表中使用会话变量会导致H2中的结果不确定,因为可以按任何顺序对行进行求值。

如果您使用现代版本的MySQL和H2,则可以使用ROW_NUMBER() OVER (PARTITION BY enrolmentid ORDER BY questionid)来代替这样复杂而又不可靠的表达式。

SELECT
    enrolmentid,
    questionid,
    ROW_NUMBER() OVER (PARTITION BY enrolmentid ORDER BY questionid)
FROM
    response
WHERE
    enrolmentid = 18620674
ORDER BY
    enrolmentid,
    questionid

如果您的WHERE条件始终只有一个enrolmentid,则不需要PARTITION BY子句,ROW_NUMBER() OVER(ORDER BY questionid)就足够了。