Skip to content
Advertisement

SQL – If id exists in table1, then insert record into table2

I have the following problem. I have an accounts and a scoreboard table and I try to reset all values on the end of the month in the scoreboard by inserting a new record with the value 0.

SET @mid = (SELECT MAX(id) AS mid FROM accounts);

WHILE (@mid > 0)
BEGIN
    IF @mid NOT IN (SELECT id FROM accounts) DO CONTINUE;
    INSERT INTO scoreboard("uid", "balance", "date") VALUES (@mid, 0,(SELECT CURRENT_DATE()));
    SET @mid = @mid - 1;
END

But whatever I try it breaks and I have no idea why.

MySQL: mysqlnd 5.0.12-dev – 20150407

MariaDB: 10.3.27-MariaDB-0+deb10u1

Example:

accounts

id name
1 Play_it
3 User2

scoreboard

uid balance date
1 20 2021-03-09

Expected:

scoreboard

uid balance date
1 20 2021-03-09
1 40 2021-03-31
3 30 2021-03-31
1 0 2021-04-01
3 0 2021-04-01

Advertisement

Answer

Do you want something like this?

insert into scoreboard (uid, balance, date)
    select a.id, 0, curdate()
    from accounts a;

This inserts a new row in scoreboard for each row in account.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement