根据Where条件,使用子表的PK更新父表的FK列

时间:2013-01-14 14:19:45

标签: sql sql-server sql-server-2005

select t1.columnFK from table1 t1, table2 t2 where t1.columnFK=t1.columnpk AND t2.somecolumn='value1'



select t2.columnPK from table2 t2 where t2.somecolumn='value2'

所以我必须使用第二个值更新第一个select语句中的所有值。 我尝试写这样的更新查询:

UPDATE table1
SET table1.columnFK = table2.columnPK
From tabel1 t1, table2 t2
Where t1.columnfk=t2.columnpk AND somevalue='value2'

这是关系 table2.columnpk引用为table1.coulmnfk table1.hbm.xml

<many-to-one
            name="table2"
            column="&quot;coulmnfk&quot;"
            class="table2class"
            cascade="none"/>

表2关系如下:

<set name="table1" table="&quot;table1&quot;" inverse="true"  cascade="none">
                <key column="&quot;coulmnFK&quot;"/>
                <one-to-many class="table1"/>
            </set>

不确定我将如何包含第一个条件。

1 个答案:

答案 0 :(得分:1)

我仍然认为你的参照完整性有点奇怪。通常子表fk用父pk更新。

以下是您可能需要使用的逻辑,假设您在您的孩子身上有一个父pk作为fk并且您尝试将子pk作为fk添加到父表...使用join

UPDATE parent
SET parent.childPK = child.PK    
FROM
    Parent
    JOIN
    child ON parent.PK = child.ParentPK
WHERE parent.somecolumn in ('value1','value2')
;
相关问题