Introduction
You use UPDATE with JOIN to change data in one table based on matching data in another table. It helps update related information easily.
UPDATE table1 JOIN table2 ON table1.common_field = table2.common_field SET table1.field_to_update = new_value WHERE some_condition;
UPDATE employees JOIN departments ON employees.dept_id = departments.id SET employees.salary = employees.salary * 1.1 WHERE departments.name = 'Sales';
UPDATE orders JOIN customers ON orders.customer_id = customers.id SET orders.status = 'Shipped' WHERE customers.region = 'West';
CREATE TABLE employees (id INT, name VARCHAR(20), dept_id INT, salary DECIMAL(10,2)); CREATE TABLE departments (id INT, name VARCHAR(20)); INSERT INTO employees VALUES (1, 'Alice', 10, 50000), (2, 'Bob', 20, 60000), (3, 'Carol', 10, 55000); INSERT INTO departments VALUES (10, 'Sales'), (20, 'HR'); UPDATE employees JOIN departments ON employees.dept_id = departments.id SET employees.salary = employees.salary * 1.1 WHERE departments.name = 'Sales'; SELECT id, name, salary FROM employees ORDER BY id;
UPDATE with JOIN in MySQL?table1 using table2 with a JOIN on id in MySQL?users(id, name, city_id)cities(id, city_name)UPDATE users u JOIN cities c ON u.city_id = c.id SET u.name = CONCAT(u.name, ' - ', c.city_name) WHERE c.city_name = 'Paris';
UPDATE orders o JOIN customers c SET o.status = 'shipped' ON o.customer_id = c.id WHERE c.region = 'West';
products(id, price, category_id)categories(id, discount_percent)products.price applying the discount using UPDATE with JOIN?Pass the test and this pattern moves unknown