SQL Update Query - Reversing a reference
I'm new to SQL, so this isn't too complicated.
I have two tables, with currently no Foreign Key Constraint implemented:
Table Foo
============
ID | BarID
------------
1 | NULL
2 | NULL
3 | NULL
and
Table Bar
============
ID | FooID
------------
101 | 1
102 | 2
103 | 3
As you can see, the Bar table rows know which Foos they relate to, but the Foo table rows do not know which Bars they relate to. I want to switch this around, so I get:
Table Foo
============
ID | BarID
------------
1 | 101
2 | 102
3 | 103
I want a SQL query that will set te BarID on the Foo table. In pseudo code:
for each Foo in FooTable:
Bar = select B开发者_Python百科ar from BarTable where Bar.FooID == Foo.ID
set Foo.BarID = Bar.ID
set Bar.FooID = NULL
Thanks
EDIT: I'm using Microsoft SQL Server 2008
update foo set
BarID = (select ID from Bar where FooId = Foo.ID);
It seems you want to clear out references from Bar to Foo. If so, do this:
update Bar set FooID = null;
UPDATE Foo SET BarId=(SELECT Id FROM BAR WHERE Fooid=foo.id)
UPDATE Foo
JOIN Bar ON Bar.FooID = Foo.ID
SET Foo.BarID = Bar.ID
This should do it
UPDATE Foo
USING Bar
SET BarID=Bar.ID
WHERE Foo.ID = Bar.FooID;
精彩评论