根据mysql中其他表中的匹配值更新列

时间:2012-09-29 06:41:59

标签: mysql sql join sql-update match

我有两个表日历和客户表。日历表有一个"客户"列有客户表" ID"作为价值。但遗憾的是,此日历客户字段值错误地填充了其他值。两个表都有这些公共字段Date,SeatingID和BusID。如何根据这些常用字段更新日历表客户字段?。

以下是两个表格的结构。

客户表 enter image description here

日历表

enter image description here

4 个答案:

答案 0 :(得分:7)

您可以UPDATE从第一个表CustomerCalendar Customer JOIN 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. 字段SET这两个表如下:

JOIN

c1.SeatingID = c2.SeatingID AND c1.BusID = c2.BusID子句中,您可以设置要更新的列,也可以基于任何谓词{{1}} {{1}}这两个表,我使用{{1}}但您可以选择适合您需求的产品。

Here is a SQL Fiddle demo

答案 1 :(得分:1)

试试这段代码:

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链接到更多信息abaout update

答案 2 :(得分:1)

update calendar ca left join customer c 
on c.DateofTravel=ca.Date and c.SeatingID=ca.SeatingID and c.BusID=ca.BusID 
set 
ca.Customer=c.ID;

答案 3 :(得分:0)

使用此查询,它将帮助您从另一个表列更新表列:

UPDATE tableName1 AS tb1
INNER JOIN tableName2 AS tb2 
ON (tb1.columnName= tb2.columnName) 
SET tb1.updatedColumn = tb2.updatedColumnValue
WHERE ADD HERE CONDITION IF REQUIRED