We help IT Professionals succeed at work.

Update row with another rown from the same table

DarkHill
DarkHill asked
on
Medium Priority
1,011 Views
Last Modified: 2012-05-06
Using MySQL, I would like to update a row from a table using another row from that same table, is this possible? Ideally something like this:

UPDATE table SET row 1 = row 2
DELETE row 2

I need to do this for many tables and I don't want to have to write a script in PHP for each table. It would be easy enough to read the data into PHP and then run another query to update the first row, but I will then have to do this for each table which is a pain.
Comment
Watch Question

Data Warehouse / Database Architect
CERTIFIED EXPERT
Commented:
Hi DarkHill,

You'll need to join the table (to itself) based on some key.

UPDATE table1,table2 SET table1.column = table2.column
WHERE table1.rowID = table2.rowID;

Of course, the filter can be as complicated as necessary to map the correct rows.  :)


Good Luck,
Kent

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts

Author

Commented:
Hey Kent,

Thanks, that put me on the right path, I did a test now and this seems to work pretty well:

UPDATE tester t1, tester t2 SET t1.title = t2.title, t1.more = t2.more
WHERE t1.id=1 and t2.id = 2
Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.