数据库中有a、b两表,两表的对应关系为1:M,即a表的1条记录可能对应b表的多条记录。现在想根据b表中的最近更新来对a表进行排序。之前实现的时候没有深入处理,只是进行了随机排序。
之前的SQL:
SELECT md.title,md.uuid,count(v.id) as c FROM mdversion v LEFT JOIN metadata md ON md.uuid=v.uuid WHERE md.title IS NOT NULL group by md.uuid,md.title
修改后,将ab两表先联合在排序查询,即可满足要求:
SELECT md.title,md.uuid,count(v.id) as c FROM mdversion v LEFT JOIN (select m.uuid,m.title,m.description,max(v.ts_created) as ts_created from mdversion v left join metadata m on v.uuid=m.uuid group by m.uuid,m.title,m.description) md ON md.uuid=v.uuid WHERE md.title IS NOT NULL group by md.uuid,md.title,md.ts_created order by md.ts_created desc
关键点:先将需要排序的要素提取到临时表中,然后再进行对应的联合处理。
发表回复