MySQL UPDATE与JOIN到子选择

时间:2014-02-02 17:59:39

标签: mysql sql database

我有一个名为sagepaydirect__transactions的表,我正在通过迁移将其response字段设置为名为response的表的sagepaydirect__responses字段。

两个通过名为sagepaydirect__requests的表格在vendor_tx_code字段中_分隔字符串的最后4位数字上进行连接。

问题在于sagepaydirect__requests在加入sagepaydirect__transactions时会有多行。我想做的是做JOIN,以便UPDATE从sagepaydirect__transactions中的ID中取值,其值在数字上更高。

这是我对查询的尝试,但投诉是t.id不存在。

UPDATE sagepaydirect__transactions t
INNER JOIN (
        SELECT * FROM sagepaydirect__requests rq
        WHERE SUBSTRING_INDEX(rq.vendor_tx_code, '_', -1) = t.id
        ORDER BY id DESC
        LIMIT 1
) rq_table
ON t.id = SUBSTRING_INDEX(rq_table.vendor_tx_code, '_', -1)
INNER JOIN sagepaydirect__responses rs
ON rq.id = rs.request_id
SET t.response = rs.status_detail

1 个答案:

答案 0 :(得分:1)

您正尝试在from子句中使用相关子查询。那不行。以下使用聚合来获取最大id,然后继续使用join

UPDATE sagepaydirect__transactions t INNER JOIN
       (SELECT SUBSTRING_INDEX(rq.vendor_tx_code, '_', -1) as val, max(id) as maxid
        FROM sagepaydirect__requests rq
        WHERE SUBSTRING_INDEX(rq.vendor_tx_code, '_', -1) = t.id
        group by id SUBSTRING_INDEX(rq.vendor_tx_code, '_', -1)
      ) rq
      ON t.id = rq.val INNER JOIN
      sagepaydirect__responses rs
      ON rq.id = rs.request_id
    SET t.response = rs.status_detail;