使用另一个表更新一个表

时间:2015-11-17 12:54:23

标签: sql sqlite join sql-update

我已经建立了一个数据库,其中有这些表:

companies (a,b,nazov,ic_dph,mesto,ulica_cislo,psc) 
finan (nazov,ic_dph,mesto,ulica_cislo,psc)

在表companies中,列ic_dph,mesto,ulica和psc为空。我想用finan表中的列更新这些列。我尝试了很多 SQLite3 查询,但都没有。

使用更新:

UPDATE companies SET companies.ic_dph = finan.ic_dph, companies.mesto = finan.mesto, companies.ulica_cislo = finan.ulica_cislo, companies.psc=finan.psc WHERE companies.nazov = finan.nazov

使用加入:

CREATE TABLE new_table AS (SELECT * FROM companies JOIN finan)

两个查询都返回一些语法错误。

你能给我一个建议吗?

1 个答案:

答案 0 :(得分:1)

如果您需要替换所有值,可能最好的方法是删除行并插入新值:

create temporary table t as 
    select c.a, c.b, c.nazov, f.ic_dph, f.mesto, f.ulica, f.psc 
    from companies c left join
         finan f
         on c.nazov = f.nazov;

delete from companies;

insert into companies(a, b, nazov, ic_dph, mesto, ulica, psc)
    select a, b, nazov, ic_dph, mesto, ulica, psc
    from t;

请小心使用此方法。

另一种方法是一堆相关的子查询。首先,请确保您在finan(nazov)上有索引。然后:

update companies c
    set ic_dph = (select ic_ph from finan f where f.nazov = c.nazov),
        mesto = (select mesto from finan f where f.nazov = c.nazov),
        ulica = (select ulica from finan f where f.nazov = c.nazov),
        psc = (select psc from finan f where f.nazov = c.nazov)
    where exists (select 1 from finan f where f.nazov = c.nazov);