Mysql - How to use UPDATE with SELECT???

Discussion in 'MySQL' started by rahulephp, Jul 30, 2010.

  1. #1
    Hi,

    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
    [​IMG]


    related_category table
    [​IMG]

    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:
    
    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
    )
    Code (markup):
    But it doesn't works,
    Please assist. Thanks in advance
     
    rahulephp, Jul 30, 2010 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    Best way would be to do a join.

    
    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
    
    Code (markup):
     
    jestep, Jul 30, 2010 IP
  3. rahulephp

    rahulephp Peon

    Messages:
    45
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Thanks, thats exactly i was looking for. It works great for me.
     
    rahulephp, Jul 30, 2010 IP