3

I currently trying to update rows using loop in a table.

I have fields named 'id' and 'visitor_id'. 'id' column is auto increment but 'visitor_id' is not. There are already existing data inside the table and both columns look like this.

'id'     'visitor_id'
 1            0
 2            0
 3            0
 4            0
 5            0

So what I want is I want these both columns to have the same value.

'id'     'visitor_id'
 1            1
 2            2
 3            3
 4            4
 5            5

I try and search on how to loop and update the value but still no luck.This is the code that i try.

DELIMITER $$

DROP PROCEDURE IF EXISTS insert_loop $$

CREATE PROCEDURE insert_loop ()
BEGIN
    DECLARE i int DEFAULT 1;
    WHILE i <=30 DO
        UPDATE test_db.visitor_visit SET visitor_id=i WHERE id=i;
        SET i = i + 1;
    END WHILE;
END $$

CALL insert_loop();

I will accept any other method that might help my situation. Thanks! :)

2 Answers 2

3

you have to use the trigger(after insert) in order to solve this problem, try this query:

CREATE TRIGGER aa BEFORE INSERT ON ab FOR EACH ROW SET NEW.visitor_id = new.id

just on your first insert, set the 'visitor_id = null' and then set it in any value you wish because it will directly take the 'id' value in the same row. hope is that useful.

Sign up to request clarification or add additional context in comments.

Comments

2

A simple update query can do the same thing.

UPDATE test_db.visitor_visit SET visitor_id=id 
WHERE id BETWEEN 1 and 30

1 Comment

Omg i can't believe I didnt think about this. I really need to have enough sleep from now on. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.