mysql - Select latest updated categories based on their items -
i have mysql database , there's categories
table this:
id name parent -------------------------- 1 news 0 2 analysis 0 3 europe 1 4 middle east 1 5 asia 1 6 americas 1 7 commentaries 2 8 interviews 2 9 articles 2 10 reports 2
and items
table this:
id created catid title --------------------------------------------- 1 2013-08-12 20:15:00 3 foo 2 2013-08-12 19:15:00 3 bar 3 2013-08-12 18:15:00 4 foobar 4 2013-08-12 17:15:00 4 barfoor 5 2013-08-12 16:15:00 8 boofar 6 2013-08-12 15:15:00 9 farfar 7 2013-08-11 16:45:00 10 farfarbar 8 2013-08-11 16:15:00 5 foofoobar 10 2013-08-10 16:15:00 7 foobarbar
what want list categories children of specified parent , have latest items in them. example if want latest updated categories of news (catid=1) section, result be:
3 europe 4 middle east 5 asia
note results ordered last update time.
please consider due large amount of records, performance of query important.
a join works pretty fast. use group enable aggregate max()
-function sort output.
in where
-clause can choose parent-id want search for.
select c.id, c.name categories c inner join items on c.id = i.catid c.parent = 1 group c.id order max(i.created) desc
edit
in event of single nestings, can change query follows:
select c.id, c.name categories c inner join items on c.id = i.catid c.parent = 1 or c.parent in (select id categories c.parent = 1) group c.id order max(i.created) desc
if need more nestings, you'd need create stored procedures. more information can found here.
Comments
Post a Comment