Author Topic: Mysql - How to use UPDATE with SELECT???  (Read 453 times)

0 Members and 1 Guest are viewing this topic.

Offline rahulephpTopic starter

  • Irregular
  • Posts: 34
    • View Profile
Mysql - How to use UPDATE with SELECT???
« on: July 30, 2010, 03:11:57 AM »
Mysql - How to use UPDATE with SELECT???

I have two tables:
1) products_category
-cat_id
-cat_name

2) related_category
-rel_cat_id (exaclty same as products_category.cat_id==related_category.rel_cat_id)
-rel_cat_name

products_category table



related_category table



I want to get cat_name from products_category and want to store in rel_cat_name in related_category tabel. and the query should be only one.

Not sure how will it works.
I thought it would be something like:
Code: [Select]
UPDATE related_category
SET related_category.rel_cat_name =
(
SELECT product_category.cat_name FROM product_category
INNER JOIN related_category
ON related_category.rel_cat_id = product_category.cat_id
)

But it doesn't works,
Please assist. Thanks in advance
« Last Edit: July 30, 2010, 03:13:13 AM by rahulephp »

Offline Mchl

  • Staff Alumni
  • Freak!
  • *
  • Posts: 8,582
  • Gender: Male
  • That's Largo in my avatar, not me.
    • View Profile
    • FlingBits
Re: Mysql - How to use UPDATE with SELECT???
« Reply #1 on: July 30, 2010, 04:33:52 AM »
Not at all.

Use join in UPDATE's table reference clause

Code: [Select]
UPDATE related_category AS rc
INNER JOIN product_category AS pc
ON rc.rel_cat_id = pc.cat_id
SET rc.rel_cat_name = pc.cat_name
NetBeans fanatic | ExtJS masochist | C++ denier
PHP4 & MySQL4 are no longer supported.
PHPFreaks Tutorials | PHP Debugging: A Beginner's guide | PHP Security Tutorial || How To Ask Questions The Smart Way
Flingbits tutorials | Class Autoloading

Offline rahulephpTopic starter

  • Irregular
  • Posts: 34
    • View Profile
Re: Mysql - How to use UPDATE with SELECT???
« Reply #2 on: July 30, 2010, 05:00:28 AM »
Thank you buddy,
I got the solutions. Here it is:

Code: [Select]
UPDATE related_category
INNER JOIN
product_category
ON related_category.rel_cat_id = product_category.cat_id
SET related_category.rel_cat_name = product_category.cat_name

Offline Mchl

  • Staff Alumni
  • Freak!
  • *
  • Posts: 8,582
  • Gender: Male
  • That's Largo in my avatar, not me.
    • View Profile
    • FlingBits
Re: Mysql - How to use UPDATE with SELECT???
« Reply #3 on: July 30, 2010, 06:48:48 AM »
That's pretty much the same, except I used aliases to make it less verbose. ;)
NetBeans fanatic | ExtJS masochist | C++ denier
PHP4 & MySQL4 are no longer supported.
PHPFreaks Tutorials | PHP Debugging: A Beginner's guide | PHP Security Tutorial || How To Ask Questions The Smart Way
Flingbits tutorials | Class Autoloading

Offline rahulephpTopic starter

  • Irregular
  • Posts: 34
    • View Profile
Re: Mysql - How to use UPDATE with SELECT???
« Reply #4 on: July 30, 2010, 06:50:48 AM »
Yeah.. i am thankful to you for this  ;)