如何在进行内部联接MySql时更新2个表?

时间:2013-05-23 19:40:02

标签: mysql sql-update inner-join

我正在尝试在MySql中更新2个不同的表,而我将它们内部相互连接。

这是我最后一次尝试返回以下错误

#1064 - 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 'FROM ticketing_system_issues AS i INNER JOIN ( SELECT d.notes, d.issue' at line 8

UPDATE i, dis
SET i.category_id = 5,
i.priority = 1,
i.issue_title = "This is a test",
dis.notes = "This is a notes test",
i.modified_on = NOW(),
i.modified_by = 2
FROM ticketing_system_issues AS i
INNER JOIN (
SELECT d.notes, d.issue_id FROM ticketing_system_discussions AS d
INNER JOIN (
SELECT issue_id, MIN(created_on) AS min_time FROM ticketing_system_discussions
GROUP BY issue_id
) AS sub ON sub.issue_id = d.issue_id AND d.created_on = sub.min_time

) AS dis ON i.issue_id = dis.issue_id
WHERE i.issue_id = 58

要进行更多测试,请使用以下查询来查找我要更新的字段

SELECT i.category_id, i.priority, i.issue_title, dis.notes, i.modified_on, i.modified_by
FROM ticketing_system_issues AS i
INNER JOIN (
SELECT d.notes, d.issue_id FROM ticketing_system_discussions AS d
INNER JOIN (
SELECT issue_id, MIN(created_on) AS min_time FROM ticketing_system_discussions
GROUP BY issue_id
) AS sub ON sub.issue_id = d.issue_id AND d.created_on = sub.min_time

) AS dis ON i.issue_id = dis.issue_id
WHERE i.issue_id = 58

1 个答案:

答案 0 :(得分:3)

您想要的一般语法是:

UPDATE table1 AS t1
JOIN table2 AS t2 ON <join condition>
SET t1.col1 = val1, t1.col2 = val2, t2.col3 = val3
WHERE <filter condition>

您的SET条款位置错误。

您的问题中无法执行特定的UPDATE,因为您尝试分配给子查询,而不是表。您必须将它分隔为您指定的表和您加入的子查询:

UPDATE ticketing_system_issues AS i
INNER JOIN ticketing_system_discussions AS dis ON i.issue_id = dis.issue_id
INNER JOIN (SELECT issue_id, MIN(created_on) AS min_time
            FROM ticketing_system_discussions
            GROUP BY issue_id) AS sub
      ON sub.issue_id = dis.issue_id AND dis.created_on = sub.min_time
SET i.category_id = 5,
    i.priority = 1,
    i.issue_title = "This is a test",
    dis.notes = "This is a notes test",
    i.modified_on = NOW(),
    i.modified_by = 2
WHERE i.issue_id = 58