简体   繁体   中英

mysql update table with values from another table?

I am trying to update my table 'supplier_stats' with the values from my other table 'supplier_change_request'.

My two tables look like the following:

Supplier_change_request

id   |   user_id   |   company_name   |   supplier_number
1        123           hewden             V0001

Supplier_stats

Id | user_id | company_name  |  address  |   reference   | supplier_number
1    123       pie              n/a          12345         V0001
2    145       gates            n/a          12345         V0002

Here is my MySQL:

$reference = '12345'

$query = "UPDATE supplier_stats 
SET supplier_stats.company_name = (
    SELECT supplier_change_request.company_name 
    FROM supplier_change_request
    WHERE supplier_change_request.reference = '$reference' AND supplier_change_request.supplier_number = supplier_stats.supplier_number";
mysql_select_db('hewden1');
$retval = mysql_query( $query, $conn )

by my calculation this should be setting the value of company_name where supplier_number is 'V0001' in my table 'supplier_stats' to 'hewden'. However the company_name is not being updated.

Can someone please show me where I am going wrong? Thank you in advance

I think the syntax is a bit off in your query and that it should look like this (just the SQL, adapt to PHP as needed):

UPDATE supplier_stats ss
JOIN supplier_change_request scr ON scr.supplier_number = ss.supplier_number
SET ss.company_name = scr.company_name 
WHERE ss.reference = '$reference' 

The column reference pointed to the supplier_change_request in your sample query, but to supplier_stats in your sample data - I assumed the sample data was correct; change if not.

This query should change the company_name in supplier_stats from pie to hewden .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM