在SELECT语句中设置两个变量-MySQL

时间:2018-11-14 09:34:32

标签: mysql sql

我正在使用下面的代码,这些代码在mysql中执行,但是在通过java程序时遇到错误,因为java程序无法读取分号...对于Java,这是3条语句。我需要执行此查询(设置两个变量,然后在一个查询中选择):

set @row_number:=0;set @PROMOTION_ID_NO:='';
SELECT 
     @row_number:=CASE 
        WHEN @PROMOTION_ID_NO=PD.PROMOTION_ID THEN @row_number + 1
        ELSE 1
    END AS SEQ,
     @PROMOTION_ID_NO:=PD.PROMOTION_ID AS PROMOTION_ID,
    PD.CONDITION_CODE,
    PM.PROMOTION_code,
    PD.CONDITION_TYPE
FROM
    POS_PROMOTION_DISCOUNT PD , POS_PROMOTION_MASTER PM WHERE 
    PD.PROMOTION_ID = PM.PROMOTION_ID
AND PD.STORE_NO = 'G121';

1 个答案:

答案 0 :(得分:0)

  • 您可以将SET语句移到单独的Derived Table,然后与其他表一起对该表进行CROSS JOIN
  • 请不要使用基于旧逗号的隐式联接,而不要使用现代Explicit Join based syntax。我已改为使用JOIN .. ON

请尝试以下操作:

SELECT 
     @row_number:=CASE 
                    WHEN @PROMOTION_ID_NO=PD.PROMOTION_ID THEN @row_number + 1
                    ELSE 1
                  END AS SEQ,
     @PROMOTION_ID_NO:=PD.PROMOTION_ID AS PROMOTION_ID,
    PD.CONDITION_CODE,
    PM.PROMOTION_code,
    PD.CONDITION_TYPE
FROM
    POS_PROMOTION_DISCOUNT PD 
JOIN POS_PROMOTION_MASTER PM ON PD.PROMOTION_ID = PM.PROMOTION_ID
CROSS JOIN (SELECT row_number:=0, @PROMOTION_ID_NO:='') AS user_init 
WHERE 
  PD.STORE_NO = 'G121';