SQL update table values from a different table
-
13-06-2021 - |
Question
I have 2 tables xcart_products which has productid , meta_description
and many other fields . The 2nd table is xcart_extra_field_values which has ( productid fieldid and value
)
I need to copy the value of fieldID = 1
of xcart_extra_field_values
into
the meta_description
column of the xcart_products
table where the Productid
are same.
UPDATE `xcart_products` SET meta_description = ( SELECT value FROM
xcart_extra_field_values WHERE fieldid = 1 AND
xcart_extra_field_values.productid = xcart_products.productid )
WHERE
xcart_extra_field_values.productid = xcart_products.productid ;
I wrote the above SQL but i am getting an error
#1054 - Unknown column 'xcart_extra_field_values.productid' in 'where clause'
Solution
I hope this will work for you:
UPDATE `xcart_products`, `xcart_extra_field_values` SET xcart_products.meta_description = xcart_extra_field_values.value
WHERE
xcart_extra_field_values.fieldid = 1
AND
xcart_products.productid = xcart_extra_field_values.productid
OTHER TIPS
You need to the second table name to your query, because it is used in the query, even though you are not changing any data in it.
UPDATE xcart_products, xcart_extra_field_values
You could use the multiple-table UPDATE
syntax to join the tables instead:
UPDATE xcart_products JOIN xcart_extra_field_values USING (productid)
SET xcart_products.meta_description = xcart_extra_field_values.value
WHERE xcart_extra_field_values.fieldid = 1;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow