问题
I have 3 tables:
tbl_indicator grp_nbr, sect_nbr, indicat 1 100 p 2 101 s
tbl_group grp_id, grp_nbr, sect_nbr, indicat 333 1 100 a 555 1 100 p 444 2 101 s 222 2 101 y
Here (in tbl_group) grp_id is Primary Key
tbl_order order_id, grp_id 5000 333 5001 555 5002 555 5003 555 5004 444 5005 444 5006 222
Here (in tbl_order) grp_id is a Foreign Key to grp_id in tbl_group.
In table tbl_indiactor, for one set of grp_nbr and sect_nbr there is an indicat, for the same set of grp_nbr and sect_nbr there is a correct indicat(555,1, 100, p) and a junk indicat(333, 1, 100, a) in table tbl_group, but both these grp_id s(333, 555) are present in table tbl_orders.
Now i need to update tbl_order table in such a way that the junk grp_id s should be replaced with correct grp_id s
The output should like:
tbl_orders order_id, grp_id 5000 555 5001 555 5002 555 5003 555 5004 444 5005 444 5006 444
here is a small change
tbl_indicator
grp_nbr, sect_nbr, indicat
01 100 p
02 101 s
tbl_group
grp_id, grp_nbr, sect_nbr, indicat
333 01 100 a
555 01 100 p
444 02 101 s
222 2 101 y
Here (in tbl_group) grp_id is Primary Key
the junk data(indicat) in group table (222, 22, 101, y) the grp_nbr has one character length but the grp_nbr in tbl_indicat has two character length... how can we handle this??
回答1:
First, figure out which records need to be updated:
select *
from tbl_order o
inner join tbl_group g on
g.grp_id = o.grp_id
inner join tbl_indicator i on
i.grp_nbr = g.grp_nbr
and i.sect_nbr = g.sect_nbr
where
g.indicat != i.indicat
Now, modify the query to update those records with the correct grp_id. Notice that I've added an extra join to the tbl_group table with an alias of "g2". This will be the correct group.
update o set
o.grp_id = g2.grp_id
from tbl_order o
inner join tbl_group g on
g.grp_id = o.grp_id
inner join tbl_indicator i on
i.grp_nbr = g.grp_nbr
and i.sect_nbr = g.sect_nbr
inner join tbl_group g2 on
g2.grp_nbr = i.grp_nbr
and g2.sect_nbr = i.sect_nbr
and g2.indicat = i.indicat
where
g.indicat != i.indicat
Note that due to the inner join on tbl_group g2, the records will not be updated if there does not exist any tbl_group record where indicat matches the indicat value of its associated tbl_indicator record.
来源:https://stackoverflow.com/questions/9083716/sql-update-help-me