我有一个名为“文章”的表格。 文章(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 |
+----+-------------------------+--------
现在连同此OUTPUT,我必须在每个类别中找到COUNT个文章。 我需要的输出是:
+----+-------------------------+-------+-------+
| id | article| category | title | Count |
+----+-------------------------+-------+-------+
| 2 | a2 | a | ta2 | 2 |
| 5 | b3 | b | tb3 | 3 |
| 8 | c3 | c | tc3 | 3 |
+----+-------------------------+----------------+
帮我查询???????? /
答案 0 :(得分: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
答案 1 :(得分: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
感谢那些试图提供帮助的人
答案 2 :(得分:-1)