你如何更新mysql中另一个表的多个字段?

The*_*mer 2 mysql sql sql-update

这是我想要完成的查询:

update amdashboard
set (ASCID, ASCFirst, ASCLast, ASCOtherName, ASCAdd1, ASCAdd2,
     ASCCity, ASCState, ASCZip, ASCZip4, ASCY2007, ASCY2008, ASCY2009,
     ASCY2010, ASCY2011, ASCY2012, ASCEthnicity, ASCGender, ASCMaritalStatus)
= (select id, firstname, lastname, listingspousename, add1, add2,
          city, state, zip, zip4, y2007, y2008, y2009,
          y2010, y2011, y2012, Ethnicity, Gender, MaritialStatus
     from ASCNCOAClean
          inner join amdashboard
          on ASCNCOAClean.firstname = amdashboard.actorsfirst
          and ascncoaclean.lastname = amdashboard.actorslast)
    where exists (select id, firstname, lastname, listingspousename,
                         add1, add2, city, state, zip, zip4, y2007, y2008,
                         y2009, y2010, y2011, y2012, Ethnicity, Gender,
                         MaritialStatus
                    from ASCNCOAClean
                         inner join amdashboard
                         on ASCNCOAClean.firstname = amdashboard.actorsfirst
                         and ascncoaclean.lastname = amdashboard.actorslast);
Run Code Online (Sandbox Code Playgroud)

我不能让这个工作......在第一个括号上收到语法错误.所以,我想我只会尝试一个领域.我试过这个:

update amdashboard
set ascid = (select ascncoaclean.id
         from ASCNCOAClean 
         where ASCNCOAClean.firstname = amdashboard.actorsfirst
                           and ascncoaclean.lastname = amdashboard.actorslast)
where exists (select ascncoaclean.id
         from ASCNCOAClean 
         where ASCNCOAClean.firstname = amdashboard.actorsfirst
                           and ascncoaclean.lastname = amdashboard.actorslast);
Run Code Online (Sandbox Code Playgroud)

然而,这返回并且错误1242:子查询返回多于1行.这看起来很傻.我知道它会返回多行......我想要它,因为我需要更新多行.

我错过了什么?

Hav*_*ard 10

您想要的查询看起来像这样:

UPDATE amdashboard a, ASCNCOAClean b SET
   a.ASCID            = b.id,
   a.ASCFirst         = b.firstname,
   a.ASCLast          = b.lastname,
   a.ASCOtherName     = b.listingspousename,
   ...
   a.ASCMaritalStatus = b.MaritialStatus
WHERE a.actorsfirst = b.firstname;
Run Code Online (Sandbox Code Playgroud)

观察你将不得不替换...我没写的其余列关联.

但要小心,有些东西告诉我这个查询会对你的数据库做一些非常错误的事情,因为你没有使用唯一的密钥来关联表.如果有两个相同的记录,ASCNCOAClean.firstname你肯定会丢失数据.

还要注意它将更新现有记录amdashboard,而不是添加新记录.如果您打算将数据迁移ASCNCOACleanamdashboard,假设amdashboard是一个全新的空表,那么您想要的查询是:

INSERT INTO amdashboard (
    ASCID, ASCFirst, ASCLast, ASCOtherName, ASCAdd1, ASCAdd2, ASCCity, ASCState, 
    ASCZip, ASCZip4, ASCY2007, ASCY2008, ASCY2009, ASCY2010, ASCY2011, ASCY2012,
    ASCEthnicity, ASCGender, ASCMaritalStatus
)
SELECT
    id, firstname, lastname, listingspousename, add1, add2, city, state,
    zip, zip4, y2007, y2008, y2009, y2010, y2011, y2012, Ethnicity, Gender,
    MaritialStatus
FROM ASCNCOAClean;
Run Code Online (Sandbox Code Playgroud)