简体   繁体   中英

Retrieving and moving the last record in each group

There is a table posts that contains data as shown below: ( cover column doesn't have data for now)

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

And this is my images table :

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

I want to move the last record of each group to its own column in posts table.(last records should be deleted from images table and get inserted into posts table) So the query should be able to result as followed :

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

By using NOT EXISTS get the rows having the max id in images table. Then join it with the posts table.

Query

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

For your expected result, you can use update join to do that,

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

see demo here.

Also, if you want to delete 'last' image from table images , you can use 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

If you want to run these two query in one query, just create a procudure include these two query will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM