使用其他表中没有主键列的最新记录进行联接更新

时间:2019-08-06 10:47:56

标签: mysql

我有两个表: 1.最后订购

id  username    ordername
1   user1       null
2   user2       null
3   user3       null

2.orders

ordername    username
order1      user1
order2      user1
order3      user2
order4      user3
order5      user2
order6      user3
order7      user3

我要更新lastorder表,以便ordername列将具有orders表中的最后一个订单。 lastorder表的最终结果:

 id  username    ordername
1   user1       order2
2   user2       order5
3   user3       order7

我在订单表中没有id列,这是因为订单实际上是一个子查询结果,而不是一个实际的表,但为简单起见,我们将其视为表。 如果我有id列,我的查询将是这样的:

 update lastorder l inner join 
    (select ordername,username from orders where id in 
(select max(id) from orders group by username)) as o
    on u.username = o.username set l.ordername = o.ordername;

2 个答案:

答案 0 :(得分:0)

创建一个视图,而不是一个表。这样会自动“更新”自己。

DROP TABLE lastorder;

CREATE VIEW lastorder
AS
SELECT a.id,
       a.username,
       o.ordername
       FROM (SELECT username,
                    max(id) id
                    FROM orders
                    GROUP BY username) a
            INNER JOIN orders o
                       ON o.id = a.id;

答案 1 :(得分:0)

您可以使用子查询获取最大ID,并以此检索相关的订单名称

  update lastorder l 
  inner join (
      select  o.ordername, o.username 
      from  orders o 
      inner join  (
        select  max(id)  max_id, username
        fromn orders 
        group by username
      ) t on t.max_id  =  o.id 
  ) t2 on l.username = t2.username 
  selt l.ordername  = t.ordername  

或假设您的最后一个订单是通过max(ordername)获得的

  update lastorder l 
  inner join (
        select  max(ordename)  max_order, username
        fromn orders 
        group by username
      ) t2 on l.username = t2.username 
  sel  l.ordername  = t2.max_order