tags:

views:

125

answers:

4

I'd like to convert this for us in MySQL:

UPDATE product 
SET price = 12.95 
FROM product 
    INNER JOIN product_to_category ON product.product_id = product_to_category.product_id 
    INNER JOIN category ON product_to_category.category_id = category.category_id 
        AND category.parent_id = 39

MySQL doesn't like the FROM portion, and I'm not sure that the INNER JOINs will work as written either.

+3  A: 
UPDATE product 
SET price = 12.95 
WHERE product_id in
(SELECT product_id 
FROM product_to_category 
INNER JOIN category 
ON product_to_category.category_id = category.category_id 
WHERE category.parent_id = 39)
Paul Creasey
+1: When in doubt, subquery
OMG Ponies
MySQL still doesn't like the 'FROM product' line
Deca
@Deca: There is no `FROM PRODUCT` in the provided query.
OMG Ponies
Bah, you're right - sorry about that. Pasted the wrong clipboard into my SQL box. Thanks for this.
Deca
Perfect. Thanks again.
Deca
+1  A: 

I don't have your database, so I can't really test, but I suppose you could use the multi-table syntax for your update statement :

UPDATE [LOW_PRIORITY] [IGNORE] table_references
    SET col_name1={expr1|DEFAULT} [, col_name2={expr2|DEFAULT}] ...
    [WHERE where_condition]

Quoting the manual :

For the multiple-table syntax, UPDATE updates rows in each table named in table_references that satisfy the conditions.

In your case, something like this might do the trick :

UPDATE product, product_to_category, category
SET product.price = 12.95 
WHERE product.product_id = product_to_category.product_id 
    AND product_to_category.category_id = category.category_id 
    AND category.parent_id = 39

Hope this helps !

Pascal MARTIN
I actually only need to update one table - product - but based on criteria from the other two tables. I'll try a variant of this one, looks like it's in the right direction. Thanks.
Deca
A: 

The general syntax for a multiple-table UPDATE statement is

UPDATE <table>
    (INNER|LEFT|RIGHT|...) JOIN <table2> ON <condition> 
SET <field>=<value>
WHERE <condition>

So your statement should work if you rewrite it to

UPDATE product 
    INNER JOIN product_to_category ON product.product_id = product_to_category.product_id
    INNER JOIN category ON product_to_category.category_id = category.category_id AND category.parent_id = 39
SET price = 12.95

(untested, I don't have a mysql instance at hand)

Cassy
A: 
UPDATE product 
    INNER JOIN product_to_category ON product.product_id = product_to_category.product_id 
    INNER JOIN category ON product_to_category.category_id = category.category_id 
        AND category.parent_id = 39
SET product.price = 12.95
ʞɔıu