简体   繁体   English

通过相同ID的其他表中另一行的值更新表中的行

[英]update row of table by value of other row in other table by same id

I want update table contracts by values in contracts_history table where both of id is same of other. 我想通过contracts_history表中的值来更新表contracts ,其中两个ID彼此相同。

I write this code but not work : 我写这段代码,但不起作用:

function recover_contract($contract_id)
{
$sql = "UPDATE contracts SET ROW = (SELECT * FROM contracts_history WHERE contracts.ID = contracts_history.ID)";
$result = $this->update($sql);
return $result;
}

UPDATE: 更新:
I use this code 我用这个代码

update 
contracts a, 
contracts_history b 
set 
a.name_surname=b.name_surname 

But my table has 64 structure isn't any solution for copy all data with out type all of structure? 但是我的表具有64位结构,不是所有类型都没有结构的复制所有数据的解决方案吗? must this : 必须这样做:

$sql = "INSERT INTO `contracts_history` SELECT * FROM `contracts` 
        WHERE id='$contract_id'";

Can you try this as your Query? 您可以尝试将此作为您的查询吗?

$sql = "UPDATE contracts c 
        LEFT JOIN contracts_history h ON c.ID = h.ID 
        SET WHAT_YOU_WANT";

Since you are updating to one column, your subquery should only return one value. 由于您要更新为一列,因此subquery应仅返回一个值。

Try, 尝试,

UPDATE contracts 
SET ROW = (SELECT columnName
           FROM contracts_history 
           WHERE contracts.ID = contracts_history.ID
           LIMIT 1)

or using by using JOIN 或通过使用JOIN使用

UPDATE contracts a
       INNER JOIN contracts_history b
       ON a.ID = b.ID
SET    a.row = b.columnName

UPDATE 1 更新1

ok. 好。 so here it goes, on the first type which is updating using value from subquery, I added LIMIT at the select statement because you cannot update one column with multiple values on it or else you will get an error message. 因此,在第一种使用子查询中的值进行更新的类型上,我在select语句中添加了LIMIT ,因为您无法更新其中包含多个值的一列,否则会收到错误消息。 on the second part which is joining both tables, a.ID = b.ID is the relationship of both tables. 在连接两个表的第二部分上, a.ID = b.ID是两个表的关系。 This defines how the tables are related with each other. 这定义了表如何相互关联。 SET a.row = b.columnName , columnName is the source of the value which is basically on the table contracts_history . SET a.row = b.columnNamecolumnName是值的源,该值基本上在表contracts_history

The syntax is as follows: 语法如下:

update 
    contracts a, 
    contracts_history b 
set 
    a.col1=b.col1, 
    a.col2=b.col2 
where 
    a.id=b.id 

on that note though, you have no ID specified in the query, which means it will update ALL the rows that are in the history table. 但是请注意,在查询中没有指定ID,这意味着它将更新历史记录表中的所有行。 You can add condition like this: 您可以添加如下条件:

update 
    contracts a, 
    contracts_history b 
set 
    a.col1=b.col1, 
    a.col2=b.col2 
where 
    a.id=b.id 
    and a.id=3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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