MySQL 使用同一表中的数据进行更新

标签 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 中我无法在更新中使用的查询中使用相同的表。因此,我创建了一个子查询(见下文),但现在我收到错误,表明子查询返回的行数超过 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 新手,我不确定我是否正确构建了整个事物。

最佳答案

看起来您希望将 billtoorg_id 设置为通过联系人表匹配的经销商表中的内容。如果您尝试一次更新多于 1 行,您的技术将不起作用。

尝试:

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

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

关于MySQL 使用同一表中的数据进行更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25749041/

相关文章:

mysql - Docker mysql连接错误

mysql - 如何复制字段?

mysql - 在 where 子句中使用带有 CASE 的别名列名

python - 如何划分 2 个 VARCHAR(255) 值并插入到行中(MySQL、Python)

mysql - 如何更改mysql.sock?

mysql - 为什么我收到错误 #1136 - 列计数与第 1 行的值计数不匹配?

mysql - 使用 PDO 返回最接近表中日期的 Mysql/MSSQL

php - jQuery AJAX POST 允许在没有页面重定向的情况下发送表单数据-然后如何将数据插入 mysql

php - 数据 Excel 到 MySql

mysql - 在一个查询中选择一个值并更新状态