Mysql - 如何从具有几个WHERE条件的另一个表UPDATE表

时间:2015-06-03 11:15:12

标签: php mysql sql-update where

我有两张桌子:

table1看起来像:

  

column1 | column2 | item1 | item2 | item3 | item4 | (直到第50项)

     

值|价值|价值|价值|价值|价值| .........

table_to_update看起来像:

  

column1 | colum2 |项目

     

值|价值| item1的值

     

值|价值| item2的价值

     

值|价值| item3的价值

     

值|价值| item4的价值

     

值|价值|项目的价值......

当我在table1中更改colum1或column2的值时,我希望在table_to_update中更改这些数据。项目1-50的注意值永远不会改变

所以我可以使用这个PHP命令来更新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.item1

然后item2的值为:

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

(所有相同但table1.item1更改为table1.item2)

这样做50次,这显然不太方便

有没有办法只更改WHERE部分,例如像这样(这是错误的):

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 ....

或者我可以为50个项目编写如下命令:

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

但我不知道如何让它们从1个PHP页面运行。看起来我需要创建50个PHP页面,每个页面都有1个语句?

1 个答案:

答案 0 :(得分:0)

$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']}'");



}

我认为那就是你需要前进的地方。但它需要更多的工作而且不安全。如果有人想贡献,请继续。

相关问题