Warm tip: This article is reproduced from stackoverflow.com, please click
mysql mysql-workbench

MySQL Workbench: Insert rows after checking data in 2 rows, loop on whole table

发布于 2021-03-06 17:19:30

I have a local MySQL Server instance and the MySQL Workbench for university topics.

Following table apjournal contains start and endtimes at workstations.

  • PAID is the production order,
  • ID the running number when the starttime was scanned

table apjournal

I would like to insert rows for the transportation/buffer time after each workstation.

Conditions:

(r1 := row i, r2 := row i+1)

WHERE PAID_from_r1 = PAID _from_r1 AND ID_from_r2 > ID_from_r1

THEN 
INSERT INTO sys.apjournal (ID, PAID, RID, APID, APID_ST, Startzeit, Endzeit, DurationEvent) 
VALUES (0, PAID_from_r1, RID_from_r1, APID_from_r1, CONCAT('Puffer ',APID_from_r1), Endzeit_from r1, Startzeit_from_r2, 0);

I searched for While Loop and procedures and Subqueries with running nummers. Here are my tries.

SELECT
    -
    @ID := CASE
        WHEN @last_ID > data.actual_ID AND @last_PAID = data.acutal_PAID
        THEN @ID + 1            
        ELSE 0
    END AS ID,
    @last_ID := data.ID,
    @last_PAID := data.PAID
    #INSERT INTO sys.apjournal (ID, PAID, RID, APID, APID_ST, Startzeit, Endzeit, DurationEvent) VALUES (3000+i, 1, 1)
    -- //TODO: Weitere Felder ausgeben
FROM
    -- Die Variablen initialisieren
    (SELECT @nr:= 0, @last_ID:=1,@last_PAID:=76) AS vars,
    -- Die Daten sortieren
    (
        SELECT t.*
        FROM sys.apjournal AS t
        ORDER BY PAID
    ) AS data;
    
    
#other strategy ?

drop procedure if exists addPuffer;

DELIMITER //  

CREATE PROCEDURE addPuffer(
StartID INT,
PAID Int
)   
BEGIN
DECLARE i INT DEFAULT 0; 
WHILE (i<2000)  DO
    INSERT INTO sys.apjournal (ID, PAID, RID, APID, APID_ST, Startzeit, Endzeit, DurationEvent) VALUES (3000+i, 1, 1);
    SET i = i+1;
END WHILE;
END;
//  
CALL addPuffer(); 

The problems of structuring the procedures, matching 2 rows are new for me. The procedure should loop over the whole table.

Questioner
ChrisB
Viewed
0
Akina 2020-11-19 16:13

I think that the task can be solved with one query similar to

INSERT INTO sys.apjournal (ID, PAID, RID, APID, APID_ST, Startzeit, Endzeit, DurationEvent) 
SELECT /* DISTINCT */ 0, t1.PAID, t1.RID, t1.APID, CONCAT('Puffer ', t1.APID), t1.Endzeit, t2.Startzeit, 0
FROM apjournal t1
JOIN apjournal t2 ON t1.PAID = t2.PAID 
                 AND t1.ID < t2.ID
             /*  AND another joining conditions */
/* WHERE one more conditions */

But current question text does not allow to define what additional joining and filtering conditions needed.