用JOIN命令更新记录

时间:2018-08-07 15:22:55

标签: mysql

我有以下查询效果很好,并向我显示了tbl_staff.staff_id和tbl_lead.rlog_create_user_id值不匹配的地方。

    SELECT
tbl_staff.staff_id,
tbl_staff.username,
tbl_lead.rlog_create_user_name,
tbl_lead.rlog_create_user_id
    FROM
    tbl_staff
    JOIN tbl_lead ON tbl_staff.username = tbl_lead.rlog_create_user_name
    AND tbl_staff.staff_id <> tbl_lead.rlog_create_user_id;

查询返回的值是这样的,您可以在其中看到1014与1004不匹配。

1014    bubba   bubba   1004

我想将tbl_lead.rlog_create_user_id中的值更新为与tbl_staff.staff_id中的值相同。

我试图插入SET命令,但这给了我一个通用的语法错误:

        SELECT
    tbl_staff.staff_id,
    tbl_staff.username,
    tbl_lead.rlog_create_user_name,
    tbl_lead.rlog_create_user_id
        FROM
        tbl_staff
        JOIN tbl_lead ON tbl_staff.username = tbl_lead.rlog_create_user_name
        AND tbl_staff.staff_id <> tbl_lead.rlog_create_user_id
SET tbl_lead.rlog_create_user_id=tbl_staff.staff_id ;

实际错误是:

  

[Err] 1064-您的SQL语法有错误;查看手册   对应于您的MySQL服务器版本的正确语法,   在“ SET tbl_lead.rlog_create_user_id = tbl_staff.staff_id”附近使用   10

我尝试使用此问题将SELECT更改为UPDATE命令,但仍然无法正常工作:How can I do an UPDATE statement with JOIN in SQL?

2 个答案:

答案 0 :(得分:2)

尝试一下

UPDATE tbl_lead
JOIN tbl_staff ON tbl_staff.username = tbl_lead.rlog_create_user_name
SET tbl_lead.rlog_create_user_id = tbl_staff.staff_id 
WHERE tbl_staff.staff_id <> tbl_lead.rlog_create_user_id;

答案 1 :(得分:0)

您尝试过这样吗?

UPDATE tbl_staff, tbl_lead 
  SET tbl_lead.rlog_create_user_id = tbl_staff.staff_id
  WHERE tbl_staff.username = tbl_lead.rlog_create_user_name