【问题标题】:Retrieving and moving the last record in each group检索和移动每组中的最后一条记录
【发布时间】:2018-05-28 11:21:51
【问题描述】:

有一个表posts包含如下数据:(cover列暂时没有数据)

id   title      cover
-----------------------
1    title       -
2    title       -

这是我的images 表:

id     url     post_id
-----------------------
1    1.jpg       1
2    2.jpg       1
3    3.jpg       1
4    4.jpg       1
5    5.jpg       2
6    6.jpg       2

我想将每个组的最后一条记录移动posts表中的自己的列中。(最后一条记录应该从images表中删除并插入到posts表中)所以查询应该能够得到如下结果:

id   title      cover
-----------------------
1    title     4.jpg
2    title     6.jpg

【问题讨论】:

  • @blank 没错。它应该被删除。我编辑了我的文字。

标签: mysql


【解决方案1】:

通过使用 NOT EXISTS 获取 images 表中具有最大 id 的行。然后将其与posts 表连接起来。

查询

select t1.`id`, t1.`title`, t2.`url`
from `posts` t1
join (
  select `id`, `url`, `post_id`
  from `images` t1
  where not exists (
    select 1 from `images` t2
    where t2.`post_id` = t1.`post_id`
    and t2.`id` > t1.`id`
  ) 
) t2
on t1.`id` = t2.`post_id`;

Fiddle demo

【讨论】:

    【解决方案2】:

    为了您的预期结果,您可以使用update join 来做到这一点,

    update posts p
    join (
        select t1.post_id, t1.url
        from images t1
        join (
            select max(id) max_id, post_id from images group by post_id
        ) t2 on t1.post_id = t2.post_id and t1.id = t2.max_id
    ) t on p.id = t.post_id
    set p.cover = t.url
    

    在此处查看demo

    另外,如果您想从表 images 中删除“最后一个”图像,您可以使用 delete

    delete t1
    from images t1
    join (select max(id) max_id, post_id from images group by post_id) t2
    on t1.post_id = t2.post_id
    and t1.id = t2.max_id
    

    如果您想在一个查询中运行这两个查询,只需创建一个包含这两个查询的过程即可。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-21
      相关资源
      最近更新 更多