行号通过存储过程

时间:2016-05-10 13:31:59

标签: mysql row-number

我通过sqlyog中的SQL语句获取行号,如下所示;

SET @v_num:=0;
SET @v_type := 0;

SELECT  pd.event_id,
        @v_num := IF(@v_type = pd.event_id, @v_num + 1, 1) AS row_number,
        @v_type := pd.event_id AS dummy
        ,CONCAT(va.id,',',va.`firstname`,',',va.`lastname`,',',IFNULL(va.`picture`,'')) user_info
FROM p_details pd
INNER JOIN vw_all va ON pd.pass_for = va.`user_type` AND pd.attendee_id = va.`id` AND va.`pass_id` = pd.id
WHERE CURRENT_DATE() BETWEEN pd.start_date AND pd.end_date
AND pd.event_id IN (9,50) 
ORDER BY pd.event_id,pd.last_date_time DESC

如您所知,我们不能在存储过程中使用@v和“@v_num:= IF(@v_type = pd.event_id,@ v_num + 1,1)”。所以我无法通过mysql存储过程获取行号。

有什么想法吗?

2 个答案:

答案 0 :(得分:1)

重复通过此命令修复的值:

SELECT  tt.event_id,
        @num := IF(@type = tt.event_id, @num + 1, 1) AS row_number,
        @type := tt.event_id AS dummy,
        tt.info user_info
FROM (
    SELECT  pd.event_id
            ,CONCAT(va.id,',',va.`firstname`,',',va.`lastname`,',',IFNULL(va.`picture`,'')) info
    FROM p_details pd
    INNER JOIN vw_all va ON pd.pass_for = va.`user_type` AND pd.attendee_id = va.`id` AND va.`pass_id` = pd.id
    WHERE CURRENT_DATE() BETWEEN pd.start_date AND pd.end_date
    AND   pd.last_date_time IS NOT NULL
    ORDER BY pd.event_id,pd.last_date_time DESC
    )tt 

答案 1 :(得分:0)

为什么你认为你不能在存储过程中使用这种技术? 只需将CREATE PROCEDURE语句包装在代码中,如下所示:

CREATE PROCEDURE testRowNum ()
BEGIN
SET @v_num:=0;
SET @v_type := 0;

SELECT  pd.event_id,
        @v_num := IF(@v_type = pd.event_id, @v_num + 1, 1) AS row_number,
        @v_type := pd.event_id AS dummy
        ,CONCAT(va.id,',',va.`firstname`,',',va.`lastname`,',',IFNULL(va.`picture`,'')) user_info
FROM p_details pd
WHERE Something = 'SomeValue';
END;

你已经好了。