Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

update two tables at once

Tags:

php

mysql

I'm using 5.1.41-3ubuntu12.10 for my MySQL version.

UPDATE profiledata SET aboutyou = '$aboutyou', quotes = '$quotes' 
WHERE uid = '$sess_uid'

and

UPDATE profileprivacy 
SET aboutyouPrivacy = '$aboutyouPrivacy', quotesPrivacy = '$quotesPrivacy' 
WHERE uid='$sess_uid'

$sess_uid is the same for both. I was wondering if I could combine both MySQL queries into one mysql_query.

I was thinking it would be something like SET profiledata.aboutyou = 'Just a developer.', not really sure.

like image 769
Keverw Avatar asked May 25 '11 17:05

Keverw


People also ask

How do I update two tables at once?

For instance, updating 2 different tables together in a single query/statement. This involves the use of the BEGIN TRANSACTION clause and the COMMIT clause. The individual UPDATE clauses are written in between the former ones to execute both the updates simultaneously.

Can you update two tables at once SQL?

In SQL Server, we can join two or more tables, but we cannot update the data of multiple tables in a single UPDATE statement.

How can I update two tables at once in mysql?

First, specify the table name that you want to change data in the UPDATE clause. Second, assign a new value for the column that you want to update. In case you want to update data in multiple columns, each column = value pair is separated by a comma (,). Third, specify which rows you want to update in the WHERE clause.

Can we update 2 columns at a time?

We can update multiple columns by specifying multiple columns after the SET command in the UPDATE statement. The UPDATE statement is always followed by the SET command, it specifies the column where the update is required. we can use the following command to create a database called geeks.


2 Answers

You can use a join like this:

$query = "UPDATE profiledata t1 
JOIN profileprivacy t2 ON (t1.uid = t2.uid) 
SET t1.aboutyou = '$aboutyou', 
    t1.quotes = '$quotes', 
    t2.aboutyouPrivacy = '$aboutyouPrivacy', 
    t2.quotesPrivacy = '$quotesPrivacy' 
WHERE t1.uid = '$sess_uid'";
like image 120
Adrian B Avatar answered Sep 23 '22 15:09

Adrian B


MySQL does have multi-table update support: http://dev.mysql.com/doc/refman/5.0/en/update.html.

UPDATE profiledata, profileprivacy 
SET aboutYou = ..., aboutyouPrivacy = ... 
WHERE (profiledata.uid = $sess_uid) OR (aboutyouPrivacy.uid = $sess_uid)

or something similar should do the trick.

like image 22
Marc B Avatar answered Sep 23 '22 15:09

Marc B