简体   繁体   中英

Mysql - how to UPDATE table from another table with several WHERE conditions

I have 2 tables:

table1 which looks like:

column1 | column2 | item1 | item2 | item3 | item4 | (it goes till item50)

value | value | value | value | value | value | .........

table_to_update that looks like:

column1 | colum2 | item

value | value | value of item1

value | value | value of item2

value | value | value of item3

value | value | value of item4

value | value | value of item....

when I change in table1 the value of colum1 or column2 then I want these data changed in table_to_update. Note values of items 1-50 never change

So I can update value of item1 by using this PHP commands:

UPDATE table_to_update, table1
SET table_to_update.column1 = table1.column1, table_to_update.column2 = table1.column2
WHERE table_to_update.item = table1.item1

Then value of item2 with:

UPDATE table_to_update, table1
SET table_to_update.column1 = table1.column1, table_to_update.column2 = table1.column2
WHERE table_to_update.item = table1.item2

(all the same but table1.item1 is changed to table1.item2)

And do that 50 times which is obviously not very convenient

Is there a way to only have the WHERE part changed, such as something like this (which is wrong):

UPDATE table_to_update, table1
SET table_to_update.column1 = table1.column1, table_to_update.column2 = table1.column2
WHERE table_to_update.item = table1.item1 ("THEN") table_to_update.item = table1.item2 ("THEN") table_to_update.item = table1.item3 ....

Alternatively I can write commands like below for the 50 items:

UPDATE table_to_update, table1
SET table_to_update.column1 = table1.column1, table_to_update.column2 = table1.column2
WHERE table_to_update.item = table1.item1

UPDATE table_to_update, table1
SET table_to_update.column1 = table1.column1, table_to_update.column2 = table1.column2
WHERE table_to_update.item = table1.item2

but I don't know how to have them all run from 1 PHP page. It looks like I need to create 50 PHP pages with 1 statement each?

$data = mysql_fetch_assoc(mysql_query('SELECT * FROM table1'));

foreach ($data as $row) {

    mysql_query("UPDATE table_to_update SET column1 = '{$row['column1']}', column2 = '{$row['columnd2']}' WHERE item = '{$row['item1']}'");



}

I think thats where you need to be heading. But it needs more work and is not secure. If anyone wants to contribute go ahead.

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