根据商品选择最新更新的类别

时间:2013-08-24 11:58:26

标签: mysql

我有一个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

请注意,结果按其上次更新时间排序。

请注意,由于记录量很大,查询的性能非常重要。

3 个答案:

答案 0 :(得分:2)

加入工作非常快。然后使用group by启用聚合MAX() - 函数来对输出进行排序。

WHERE - 子句中,您可以选择要搜索的父ID。

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

答案 1 :(得分: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;

答案 2 :(得分: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;