简体   繁体   中英

SQL update from same table / multiple lists and items

I need to update a table that looks like this:

No.    Item    Location        Score     Available     Price   some_more_text
1      Water   London                                  0,00
1      Water   Amsterdam       1         yes           1,11    alpha
1      Water   Burges          1         yes           1,11    alpha
2      Honey   London                                  0,00
2      Honey   Amsterdam       5         yes           5,55    omega
2      Honey   Burges          5         yes           5,55    omega
3      Spoon   London          4         yes           3,33    gamma
3      Spoon   Amsterdam       4         yes           3,33    gamma
3      Spoon   Burges          4         yes           3,33    gamma
4      Books   London                                  0,00
4      Books   Amsterdam       1         no            2,55    alpha
4      Books   Burges          1         no            2,55    alpha
5      Juice   London                                  0,00
5      Juice   Amsterdam       5         yes           5,55    beta
5      Juice   Burges          5         yes           5,55    beta
...

In the end every item in Londen should have the same properties as the according item in Burges (or Amsterdam, doesn't matter). This can't be done manually as there are so many - but I cant find a way to somehow "batch" a SQL-command to update every item with the same no.

One more problem: As it is a proprietary software I can't definitely say which language is used - but I assume it's Oracle.

You can join the table on itself in an update.

UPDATE table_X lon, table_X bur
SET lon.item=bur.item, lon.score=bur.score, etc
WHERE lon.No=bur.NO AND lon.location="London" AND bur.location="Burges";

That updates London with the data from Burges

In case it's actually SQL Server:

update lon 
set lon.item = bur.item, lon.score = bur.score, etc
from table_X lon 
inner join table_X bur
    on lon.No = bur.NO
where lon.location='London' AND bur.location='Burges';

If you're actually using Oracle you could use a merge statement (which should work with MSSQL too with a slightly different syntax):

MERGE INTO table1
USING (
  SELECT  
  t2.no t2_no,
  t2.score t2_score,
  t2.available t2_available,
  t2.price t2_price,
  t2.some_more_text t2_some_more_text
  FROM table1 t1
  JOIN table1 t2 ON t1.no = t2.no
  WHERE t1.Location='London' AND t2.Location='Burges'
) ON (no = t2_no)
WHEN MATCHED THEN UPDATE
SET score = t2_score, 
    available = t2_available,
    price = t2_price,
    some_more_text = t2_some_more_text;

See the sample SQL Fiddle

Reference documentation for merge (Oracle 11g).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM