MySQL Update使用来自同一个表的数据

时间:2014-09-09 15:52:41

标签: mysql

开始使用此查询更新同一个表中的数据:

update INVENTORY
set billtoorg_id = 
    (
        select
                dist.BillToOrg_id
        from
                INVENTORY as inv,
                contacts as cntc,
                distributors as dist
        where
                inv.f_contact_id=cntc.contact_id
                and cntc.f_dist_id=dist.dist_id
    )
where
    f_contact_id is not null
    and f_product_id = 7
    and BillToOrg_id is null

我发现这不会起作用,因为在MySQL中,我无法在Update中使用的查询中使用相同的表。所以,我创建了一个子查询(见下文),但现在我收到的错误表明子查询返回的行数超过了1行。

update inventory
set billtoorg_id = 
    (
        select
                BillToOrg_id
        from
            (
                SELECT
                    dist.BillToOrg_id
                from
                    inventory as inv,
                    contacts as cntc,
                    distributors as dist
                where 
                    inv.f_contact_id=cntc.contact_id
                    and cntc.f_dist_id=dist.dist_id
            ) as I2
    )
where
    f_contact_id is not null
    and `f_product_id` = 7
    and `BillToOrg_id` is null

有人可以建议一种方法来完成这项工作吗?我是SQL的新手,我不确定我是否正确构建了整个事物。

1 个答案:

答案 0 :(得分:0)

您希望将billtoorg_id设置为通过contacts表匹配的分配器表中的内容。如果您尝试一次更新多行,则您的技术将无效。

尝试:

update inventory as inv inner join contacts as cntc on inv.f_contact_id= cntc.contact_id
    inner join distributors as dist on cntc.f_dist_id=dist.dist_id
set inv.billtoorg_id = dist.billtoorg_id
where
    inv.f_contact_id is not null
    and `inv.f_product_id` = 7
    and `inv.BillToOrg_id` is null

编辑,因为我认为内部联接会更好。