Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update column based on matching values in other table in mysql

I have two tables calendar and customer table. Calendar table have a "customer" column which has customer table "ID" as value. But unfortunately, this calendar customer field value was wrongly populated with other values. Both tables have these common fields Date, SeatingID and BusID. How to update the calendar table customer field based on these common fields?.

Below is the structure of both tables.

Customer Table enter image description here

calendar Table

enter image description here

like image 608
Uma Avatar asked Sep 29 '12 06:09

Uma


People also ask

How do you UPDATE a column based on another column?

In such a case, you can use the following UPDATE statement syntax to update column from one table, based on value of another table. UPDATE first_table, second_table SET first_table. column1 = second_table. column2 WHERE first_table.id = second_table.

Can you modify the rows in a table based on values from another table?

You can update an entire row in one table with values from a row in another table.


2 Answers

You can UPDATE the Customer field of the second table Calendar from the first table Customer by JOINing the two tables like so:

UPDATE calendar c1
INNER JOIN Customer c2 ON c1.SeatingID = c2.SeatingID AND c1.BusID = c2.BusID
SET c1.Customer = c2.ID --or SET c1.Customer = c2.PassengerName or whatever you want.

In the SET clause, you can set the column you wish to update, and you can also JOIN the two tables based on any predicate, I used c1.SeatingID = c2.SeatingID AND c1.BusID = c2.BusID, but you can choose what is suitable for your needs.

Here is a SQL Fiddle demo

like image 66
Mahmoud Gamal Avatar answered Oct 17 '22 01:10

Mahmoud Gamal


Try this code:

UPDATE calendar cal, customer cust 
SET cal.Customer = cust.ID
where cal.SeatingID = cust.SeatingID 
and cal.BusID = cust.BusID
and cal.DATE = cust.DateOfTravel;

SQL Fiddle DEMO

Here is link to more informations abaout update.

like image 30
Robert Avatar answered Oct 17 '22 01:10

Robert