简体   繁体   English

如何从一个表中选择最后一行,然后更新另一个表的最后一行?

[英]How to select the last row from one table then update the last row of another one?

I'm doing this 我在做这个

    UPDATE table1
    SET table1.col1 = table2.col2
    FROM table2 WHERE table1.id = (SELECT MAX(id) FROM table1) AND table2.ID = (SELECT MAX(ID) FROM table2);

I have a syntax error, but I don't know how to do it. 我有语法错误,但我不知道该怎么做。

Assuming that id is unique in table1: 假设id在table1中是唯一的:

UPDATE table1 t1
    SET t1.col1 = (select t2.col2 from table2 t2 order by id desc limit 1) 
    ORDER BY t1.id DESC
    LIMIT 1;

This updates the "last" row in table1 (by id ) with the "last" row in table2 (by id ). 此更新“最后”行table1 (通过id用在“最后”行) table2 (按id )。

Your syntax doesn't work in multiple ways: 您的语法无法以多种方式工作:

  • MySQL does not support the FROM clause in UPDATE . MySQL不支持UPDATEFROM子句。
  • MySQL does not allow you to reference the table being updated in a subquery. MySQL不允许您在子查询中引用正在更新的表。

MySQL 的MySQL

   update table1
    cross join (
        select col2
        from table2
        order by id desc
        limit 1) as A
    inner join (
        select id
        from table1
        order by id desc
        limit 1) as B on (B.id = table1.id)
    set table1.col1 = A.col2

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

相关问题 如何将一行从一个表更新到另一个表? - How to update a row from one table to another? PHP:从一个 mysql 表中获取最后一行的 id 号,并使用它来更新另一个表的第一行中的字段 - PHP: Taking the last row's id number from one mysql table and using it to update a field in the first row of another table 如何从一个mySQL innodb表中选择/连接一些数据,没有重复项,并选择每个id的最后一个插入行 - How to select / join some data from one mySQL innodb table to another with no duplicates and choosing the last inserted row per id 从一个表中获取第一行和最后一行 - Get the first and the last row from one table 将联接的表从一行更新为另一行 - Update joined table from one row to another 如果在另一行中删除了一行,如何更新表 - How to update a table if a row is deleted in another one MySQL从表中的用户列表中选择每个用户的最后一行 - MySQL select last row of each one user from a list of users in a table MySQL查询:引用另一个表的最后插入行(仅使用一个php-SQL字符串) - MySQL-Query: Refer to last inserted row from another table (just with one php-SQL String) 从行选择到最后一行 - Select from row to last row 从另一个表中选择相应的记录,但仅选择最后一个 - Select corresponding records from another table, but just the last one
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM