父表按子表数量排序

发布于 2024-12-22 01:38:37 字数 206 浏览 3 评论 0原文

我有一个 tbl_user ,其中包含有关用户的信息,还有一个 tbl_article ,其中包含文章 + tbl_user 的 ID

我们有父子关系,因为每个用户可能有很多文章,这就是为什么我在文章中包含 user_id桌子。

我想列出拥有最多文章的 10 个用户...我到处搜索,但找不到它...我想过,但徒劳,我不擅长 SQL 查询。

先感谢您

I have a tbl_user , which contains information about user, and I have a tbl_article, which contains articles + the ID of the tbl_user

We have a parent-child relation, because every user may have many articles, that's why I included user_id in the articles table.

I'd like to list the 10 users that have most articles... I've searched everywhere though I couldn't find it...I've thought about it , but in vain, I'm not good in SQL Queries.

Thank you in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

峩卟喜欢 2024-12-29 01:38:37
SELECT TOP(10)
  tbl_user.id,
  COUNT(tbl_article.user_id)
FROM
  tbl_user
LEFT JOIN
  tbl_article
    ON tbl_user.id = tbl_article.user_id
GROUP BY
  tbl_user.id
ORDER BY
  COUNT(tbl_article.user_id) DESC
LIMIT
  10

根据您使用的 RDBMS,您可能需要 TOP(10)LIMIT 10 等。我将两者都包含在内,以便您可以看到,但仅使用所使用的那个由您的 RDBMS ;)

SELECT TOP(10)
  tbl_user.id,
  COUNT(tbl_article.user_id)
FROM
  tbl_user
LEFT JOIN
  tbl_article
    ON tbl_user.id = tbl_article.user_id
GROUP BY
  tbl_user.id
ORDER BY
  COUNT(tbl_article.user_id) DESC
LIMIT
  10

Depending on which RDBMS you use, you may need TOP(10) or LIMIT 10, etc. I included both so you can see, but only use the one that is used by your RDBMS ;)

丶情人眼里出诗心の 2024-12-29 01:38:37
SELECT TOP 10
    UserID, COUNT(Article)
FROM tbl_User u
INNER JOIN tbl_Article a
    ON a.Userid = u.userid
GROUP BY userid
ORDER BY COUNT(article) DESC

您所需要的只是一个GROUP BY 和一个JOIN

如果您希望包含有 0 篇文章的用户,您应该使用 LEFT JOIN

如果担心重复,您还可以选择COUNT(DISTINCT Article)

SELECT TOP 10
    UserID, COUNT(Article)
FROM tbl_User u
INNER JOIN tbl_Article a
    ON a.Userid = u.userid
GROUP BY userid
ORDER BY COUNT(article) DESC

All you need is a GROUP BY and a JOIN.

If there is a potential for users with 0 articles that you want to include, you should use a LEFT JOIN.

Optionally you can also COUNT(DISTINCT Article) if there is a concern about duplicates.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文