Mysql Event Update and search
-
03-06-2021 - |
Frage
I have a demo database where I need to set the status back to 0 each night in any table where userid = '1'
Is it possible to do that in the mySql event scheduler? Or do I need to specify each query individually?
So for example: Update "table" set status='0' where userid='1'.
Lösung
Personally, I think your currently method is the most sensible. But some other options might include:
a multi-table
UPDATE
, however you'd still have to explicitly name each table - so I'm not sure it gains you much (except perhaps a little obfuscation) and it'll almost certainly have worse performance from performing the joins:UPDATE FROM table1 JOIN table2 USING (userid) JOIN table3 USING (userid) JOIN table4 USING (userid) JOIN table5 USING (userid) SET table1.status = '0', table2.status = '0', table3.status = '0', table4.status = '0', table5.status = '0' WHERE userid = '1';
dynamically constructing your current series of
UPDATE
queries using prepared statements - but unless you are frequently changing the number or names of your tables, I don't really see the point:SET @qry = ( SELECT GROUP_CONCAT( "UPDATE `", REPLACE(table_name, "`", "``"), -- in case you have strange table names "` SET status='0' WHERE userid='1';" ) FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = 'db_name' ); PREPARE stmt FROM @qry; EXECUTE stmt; DEALLOCATE PREPARE stmt;