How can I update two tables in one query?

。_饼干妹妹 提交于 2019-12-10 12:02:21

问题


There is any way to update two tables in one query? Below is an example of my code. How can I put those two update queries in one? Thank you in advance!

   <?php
// DATABASE UPDATE
   if (isset($_POST['submit']) or isset($_GET['submit'])){

// 1st QUERY
   $db =& JFactory::getDBO();
   $query_1 = "UPDATE table_1
                  SET name     = '".$_POST["name"]."',
                      surename = '".$_POST["surename"]."'
               WHERE id=1";
   $db->setQuery($query_1);
   $db->query();

// 2nd QUERY
   $db =& JFactory::getDBO();
   $query_2 = "UPDATE table_2
                  SET team_id   = '".$_POST["team_id"]."',
                  SET team_name = '".$_POST["team_name"]."'
                  ";
   $db->setQuery($query_2);
   $db->query(); } ?>

回答1:


MySQL does actually allow updates to multiple tables in a single query (although often it makes sense for your application to do one at a time).

UPDATE table_1, table_2
SET table_1.field = <some value>, table_2.field = <some value>
WHERE table_1.field2 = table_2.field_2 
AND table_1.field_3 = <some other value>

See: http://dev.mysql.com/doc/refman/5.1/en/update.html

As other people have stated, you should look at using prepared statements.




回答2:


Use a transaction, only the InnoDB engine supports it.

mysql> start transaction; Query OK, 0 rows affected (0.00 sec)

{First Insert here}

{Second Insert Here}

mysql> commit; Query OK, 0 rows affected (0.00 sec)

Note that you have to write commit, because if you don't it wont flush it to the database.



来源:https://stackoverflow.com/questions/14347217/how-can-i-update-two-tables-in-one-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!