3

这是我要完成的查询:

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);

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

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);

但是,这会返回错误 1242:子查询返回多于 1 行。这似乎很愚蠢。我知道它会返回不止一行...我想要它,因为我需要更新多行。

我错过了什么?

4

1 回答 1

12

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

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;

观察你将不得不...用我没有写的其他列关联替换。

但要小心,有些东西告诉我这个查询会对你的数据库做一些非常错误的事情,因为你没有使用唯一键关联表。如果有两条相同的记录,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;
于 2013-04-02T02:37:31.363 回答