开发者

Update fields in MySQL table where fields in several tables are matched

I have four tables. The first contains a list of volunteers, the second a list of sites, and the third a list of projects. A project row is simply a reference to a volunteer and a site with an id and an additional column called sector.

All three tables are derived from a fourth table called legacy. I need to pull a field from each row in the legacy table in the column called sector and place it in the sector column for a corresponding row in the projects table.

In order to know I have the correct row in the le开发者_如何学运维gacy table when updating the projects table, I need to match the columns firstname and lastname from volunteers and the columns name, municipality, and province from sites with their corresponding columns in legacy.

I think my query should look something like this:

UPDATE projects, legacy
  SET
    projects.sector = legacy.sector,    
  WHERE (SUBQUERY CONTAINING COMPARISONS OF OTHER FEILDS IN OTHER TABLES SUCH AS
         volunteers.firstname = legacy.firstname
         volunteers.lastname = legacy.lasttname
         sites.province= legacy.province
         sites.municipality= legacy.municipality
         sites.name= legacy.name)

What should the subquery be?


You don't want a subquery here, you want a join.

I would write it for you but you don't show your tables so I can't.

But basically the first thing you need to do is write a SELECT with all the tables that properly connects everything. Once you do that all you need is change it to an UPDATE and you are done.


UPDATE projects
  SET sector = legacy.sector
FROM legacy
INNER JOIN sites ON sites.province = legacy.province AND/OR
         sites.municipality = legacy.municipality AND/OR
         sites.name = legacy.name
INNER JOIN volunteers ON volunteers.firstname = legacy.firstname AND/OR
         volunteers.lastname = legacy.lasttname
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜