0

我有一个名为“文章”的表。文章(id,文章,类别,标题)。我的表结构如下:

桌子 :

+----+-------------------------+---------------+
| id | article| category       | title         |
+----+-------------------------+---------------+
| 1  | a1     | a              | ta1           |
| 2  | a2     | a              | ta2           |
| 3  | b1     | b              | tb1           |
| 4  | b2     | b              | tb2           |
| 5  | b3     | b              | tb3           |
| 6  | c1     | c              | tc1           |
| 7  | c2     | c              | tc2           |
| 8  | c3     | c              | tc3           |
+----+-------------------------+---------------+

一个“类别”可以有多个与之相关的“文章”,即多个文章可以属于同一类别。我必须在每个类别中找到最后输入的文章的完整记录。

SELECT id,article,category,title FROM articles
WHERE article IN(SELECT MAX(article) FROM articles GROUP BY category)

此查询给出:

+----+-------------------------+-------+
| id | article| category       | title |
+----+-------------------------+-------+
| 2  | a2     | a              | ta2   |
| 5  | b3     | b              | tb3   |
| 8  | c3     | c              | tc3   |
+----+-------------------------+--------

现在连同这个输出,我必须在每个类别中找到 COUNT 篇文章。我需要的输出是:

+----+-------------------------+-------+-------+
| id | article| category       | title | Count |
+----+-------------------------+-------+-------+
| 2  | a2     | a              | ta2   | 2     |
| 5  | b3     | b              | tb3   | 3     |
| 8  | c3     | c              | tc3   | 3     |
+----+-------------------------+----------------+

帮我查询一下?????????/

4

3 回答 3

2

您可以使用单独的子查询计算最新文章并计算每个类别的总文章数,然后将子查询的结果连接回原始表以获取其他列,

SELECT  a.*, b.total_article
FROM    articles a
        INNER JOIN
        (
            SELECT  category, 
                    MAX(Article) last_article, 
                    COUNT(*) total_article
            FROM    articles
            GROUP   BY category
        ) b ON  a.category = b.category AND
                a.Article = b.last_article
于 2013-03-30T15:54:09.803 回答
0

我得到了我的输出使用:

SELECT a.id,
       a.title,
       a.article,
       a.category,
       b.LastArticle,
       b.TotalArticles
FROM article a
RIGHT JOIN
  (SELECT id,
          title,
          article,
          category,
          max(article) LastArticle,
          count(article) TotalArticles
   FROM article
   GROUP BY category) b ON b.LastArticle = a.article

感谢那些试图提供帮助的人

于 2013-04-01T08:19:33.800 回答
-1

尝试使用 MySQLGROUP BYORDER BY.

尝试这个:

SELECT id, article, category, title, COUNT(1) count
FROM articles
GROUP BY category
ORDER BY id DESC

这将返回每个类别的最高idcategory以及每个类别的文章数量的结果。

于 2013-03-30T15:52:16.713 回答