简体   繁体   中英

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM