2013-08-24 65 views
0

选择最新更新类别我有一个MySQL数据库,并有一个categories表是这样的:根据自己的项目

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 

而一个items表是这样的:

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 

我要的是列表到属于指定父项的子项的类别,并具有最新项目。例如,如果我想新闻(CATID = 1)节的最新更新类别,结果将是:

3 Europe 
4 Middle East 
5 Asia 

注意,结果被他们的最后更新时间排序。

请认为由于大量的记录,查询的性能非常重要。

回答

2

联接作品漂亮快速。然后使用group by启用聚合MAX()-功能对输出进行排序。

WHERE-clause中,您可以选择要搜索的父代号。

SELECT c.id, c.name 
FROM categories c 
INNER JOIN items i 
ON c.id = i.catid 
WHERE c.parent = 1 
GROUP BY c.id 
ORDER BY MAX(i.created) DESC 

SQL-Fiddle

编辑

在只有单一的嵌套的情况下,可以按如下方式更改查询:

SELECT c.id, c.name 
FROM categories c 
INNER JOIN items i 
ON c.id = i.catid 
WHERE c.parent = 1 
OR c.parent IN (SELECT id FROM categories WHERE c.parent = 1) 
GROUP BY c.id 
ORDER BY MAX(i.created) DESC 

SQL-Fiddle

我如果需要更多嵌套,则需要创建存储过程。 有关详情,请参阅here

+0

谢谢,它似乎正在工作,但如果类别变得更深一层或多层?这有可能做到吗? (我知道我没有在我的问题中提到它!) –

+0

@faridv我的查询与这个之间有什么区别? –

+0

@NaveenKumar:排序... –

1

你似乎只想要一个特定类别的孩子。看来,你问这类别行有1父母,必须在items表行:

select c.id, c.name 
from categories c 
where c.parent = 1 and 
     exists (select 1 from items i where i.catid = c.id); 

编辑:

我不知道你所说的“最新”的项目是什么意思。但是你可以通过做检查最近10个在项目表:

select c.id, c.name 
from categories c 
where c.parent = 1 and 
     exists (select 1 
       from (select i.* 
        from items i 
        order by created desc 
        limit 10 
        ) i 
       where i.catid = c.id) 
      ); 

或使用联接:

select c.id, c.name 
from categories c join 
    (select i.* 
     from items i 
     order by created desc 
     limit 10 
    ) i10 
    on i.catid = c.id 
where c.parent = 1 
group by c.id, c.name 
order by max(created) desc; 
+0

你在哪里提到查询中最新的更新类别? –

+0

最新意味着更新的基础上创建的字段。 –

+0

@faridv。 。 。我不明白这个问题。您希望按创建日期排序结果*。我原本以为你只是过滤项目表。 –

1

这里是SQLFiddle

SELECT i.catid, c.name FROM items i 
    JOIN categories c ON i.catid=c.id 
    WHERE c.parent=1 
    GROUP BY i.catid 
    ORDER BY MAX(i.created) DESC; 
+0

我想要上次更新的类别。其中有最新项目的类别。 –

+0

@faridv http://sqlfiddle.com/#!2/f7e19/5 –