mysql从另一个表中更新列的值
我有两张桌子,两个都像
id name value =================== 1 Joe 22 2 Derk 30
我需要根据每个表中的检查名称将tableA
的值的value
复制到tableB
。
这个UPDATE
语句的任何提示?
除了这个答案,如果您需要根据t2.valuedynamic更改t1.value,您可以执行例如:
UPDATE tableB INNER JOIN tableA ON tableB.name = tableA.name SET tableB.value = IF(tableA.value > 0, tableA.value, tableB.value) WHERE tableA.name = 'Joe'
你需要join这两个表格:
例如你想把tableA中的name
的值复制到tableB
,并且他们有相同的ID
UPDATE tableB t1 INNER JOIN tableA t2 ON t1.id = t2.id SET t1.name = t2.name WHERE t2.name = 'Joe'
更新1
UPDATE tableB t1 INNER JOIN tableA t2 ON t1.id = t2.id SET t1.name = t2.name
更新2
UPDATE tableB t1 INNER JOIN tableA t2 ON t1.name = t2.name SET t1.value = t2.value
第二种可能性是,
UPDATE TableB SET TableB.value = ( SELECT TableA.value FROM TableA WHERE TableA.name = TableB.name );
第二个选项也是可行的,如果你正在使用安全更新模式(并且你得到一个错误,指示你已经尝试更新一个没有使用KEY列的WHERE表),通过添加:
UPDATE TableB SET TableB.value = ( SELECT TableA.value FROM TableA WHERE TableA.name = TableB.name ) **where TableB.id < X** ;
if you have common field in both table then it's so easy !.... Table-1 = table where you want to update. Table-2 = table where you from take data. 1. make query in Table-1 and find common field value. 2. make a loop and find all data from Table-2 according to table 1 value. 3. again make update query in table 1. $qry_asseet_list = mysql_query("SELECT 'primary key field' FROM `table-1`"); $resultArray = array(); while ($row = mysql_fetch_array($qry_asseet_list)) { $resultArray[] = $row; } foreach($resultArray as $rec) { $a = $rec['primary key field']; $cuttable_qry = mysql_query("SELECT * FROM `Table-2` WHERE `key field name` = $a"); $cuttable = mysql_fetch_assoc($cuttable_qry); echo $x= $cuttable['Table-2 field']; echo " ! "; echo $y= $cuttable['Table-2 field'];echo " ! "; echo $z= $cuttable['Table-2 field'];echo " ! "; $k = mysql_query("UPDATE `Table-1` SET `summary_style` = '$x', `summary_color` = '$y', `summary_customer` = '$z' WHERE `summary_laysheet_number` = $a;"); if ($k) { echo "done"; } else { echo mysql_error(); } }