【问题标题】:Update a table's column from another table's column从另一个表的列更新一个表的列
【发布时间】:2015-09-02 11:11:04
【问题描述】:

我有两张桌子。一个是payment1,另一个是payment2。他们都有4个相互列。 Id, InvoiceNumber, TransactionCodeDate。在表payment1 中,一些TransactionCode 不同或缺失。由于只是其中一些不同,我想根据它们不同的Id 编号使用payment2 中的TransactionCode 对其进行更新。

我知道这有点令人困惑,所以让我用一个例子来解释一下:

  • 在表 payment1 中,Id 为 926,Transaction code 为 5398。在表 payment2 中,Id 为 926,但 transaction code 为 53269845。

  • 在表 payment1 中,Id 为 927,交易代码为空。在表 payment2 中,Id 为 926,但交易代码为 54895321。

我想说Ids 哪里相同,用另一个表更新TransactionCode

我试过了:

"update payment1 set payment1.TransactionCode=payment2.TransactionCode
from payment1 
join payment2 on (payment1.TransactionCode=payment2.TransactionCode)"

这是错误:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '5 from payment join table63 on (payment1.TransactionCode=payment2.TransactionCode)' at line 1

先谢谢了。

【问题讨论】:

  • 样本数据和正确的数据库标签会有很大帮助。
  • 您使用的是哪个 DBMS?后格雷斯?甲骨文?
  • 我在 phpMyAdmin 上使用 MySQL
  • 那么,付款 2 表的数据正确吗?
  • 向我们展示您的尝试。您可能需要使用update..join 语句。去谷歌上查询。尝试一下。如果它不起作用,请在此处发布错误。

标签: mysql sql join sql-update


【解决方案1】:
UPDATE Payment1 P1 
SET P1.TransactionCode= (SELECT P2.TansactionCode FROM Payment2 P2 WHERE P1.TransactionCode<>P2.TransactionCode AND P1.Id=P2.Id)

UPDATE Payment1
SET Payment1.TransactionCode= (SELECT Payment2.TansactionCode FROM Payment2 WHERE Payment1.TransactionCode<>Payment2.TransactionCode AND Payment1.Id=Payment2.Id)

其中,Payment1 和 Payment2 是表名(假设) 并且,ID & TransactionCode 是列名(假设)

【讨论】:

  • 我不明白,P2和P1是什么?
  • 它是别名@Sean。你也可以这样写.. UPDATE Payment1 SET Payment1.TransactionCode= (SELECT Payment2.TansactionCode FROM Payment2 WHERE Payment1.TransactionCodePayment2.TransactionCode AND Payment1.Id=Payment2.Id)
  • 我会尽快检查并回复您。无论如何感谢您的努力。
  • SELECT payment1.TransactionCode , payment2.TransactionCode FROM payment1 LEFT JOIN payment2 ON payment1.Id = payment2.Id 为了比较,我设法选择了两个箭头。但是,现在我想替换它们。如将 payment2.TransactionCode 转换为 payment1.TransactionCode。我必须使用更新,但它不起作用!
【解决方案2】:
    update payment1 TB1
    set TB1.Transactioncode=(select B.Transactioncode from payment2 B
    JOIN payment1 a
    on a.Transactioncode=B.Transactioncode AND B.Transactioncode=TB1.Transactioncode)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2011-04-18
    • 2011-11-25
    • 1970-01-01
    相关资源
    最近更新 更多