I have a dynamic amount of tables with the same column structure. I wish to update certain rows in all of them with a single query. Any multi-table UPDATE examples I’ve found have to do with doing different columns in different tables, and updating one table based on the value in another table. My issue is that I have the same column in all tables, and it is a dynamic number of tables.
As an example of this, I would have table_a, table_b, and table_c. All three tables would share the same structure: id and status.
I want to update the status column in all three at once to a known value.
This is the queries that I would like to essentially combine in this example.
UPDATE table_a SET status = 'closed' WHERE id = 5
UPDATE table_b SET status = 'closed' WHERE id = 5
UPDATE table_c SET status = 'closed' WHERE id = 5
Since the amount of tables is dynamic, I feel this would be cleanest with a single query. I have an array of the table names in PHP (loaded dynamically for this system) and can iterate them to form joins or concatenate a string if needed.
Here is an example of what I thought would work.
UPDATE table_a, table_b, table_c
SET status = 'closed'
WHERE id = 5
The problem with this query is that I get an error about ambiguity for the column names.
Do I need to make it like something this?
UPDATE table_a, table_b, table_c
SET table_a.status = 'closed', table_b.status = 'closed', table_c.status = 'closed
WHERE table_a.id = 5 OR table_b.id = 5 OR table_c.id = 5
I’m assuming this would work and might not be too bad, as the expected amount of tables really ranges from 1-10 maybe. However, I was really hoping for a more efficient way. Firing off individual queries might not be so bad with that few of queries, but in a big system every bit of optimization counts!
Thank you for any help.
Please note that the structure of having multiple tables with the same scheme is by design, as it is a tracker system that separates multiple locations. The example only reflects the basic structure of the idea I need to implement; the real thing is much more complicated. Also, stored procedures will not be an option in this project.
Yes, you’ll need to qualify each table / column that you want to update if they use the same logical names.
The query sees you’re looking for a logical name of ‘status’, but you’ve defined ‘status’ to be the logical name for 3 different physical locations in the database. Which one did you mean? There are many things that can be done when multiple tables are involved. So for a database to assume you want to update all of them would be very bad.