查询一张表并按另一张表中的出现次数排序

发布于 2024-10-18 03:35:44 字数 237 浏览 2 评论 0原文

我需要从“评论”表中选择我的所有评论。问题是,每个评论都会收到多个“喜欢”,这些“喜欢”存储在“喜欢”表中。

我想从“评论”表中选择所有项目,但是当每个“喜欢”在“喜欢”表中表示为一行时,请按喜欢的数量排序...

有人知道一个好方法吗这? 非常感谢, 亚尼潘 ** 编辑 ** 你好, 你是对的,抱歉。 我使用 php 作为我的服务器端,MySql 作为我的数据库...... 我忘记了这个论坛上提出的问题范围有多大......

I need to select all my comments from the 'comments' talbe. the thing is, each comment receive multiple 'likes' which are stored in the 'likes' table.

I would like to select all the items from the 'comments' table, but order then by the number of likes when each 'like' is represented as a row in the 'likes' table...

does anyone know a good way to do this?
thanks so much,
Yanipan
** edit **
Hi,
you are correct, sorry.
I use php as my server side, and MySql as my database...
I forgot how wide is the range of questions asked on this forum...

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

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

发布评论

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

评论(1

说谎友 2024-10-25 03:35:44

获取 10 个最喜欢的评论,包括那些根本没有任何喜欢的评论(左连接)(假设有两个表的简单结构:评论和喜欢):

select c.*,count(l.id) as likes
  from comments c 
    left join likes l on c.id = l.comment 
  group by l.comment
  order by count(l.id) desc 
  limit 10;

但请注意,此查询的性能将非常糟糕。因此,您很可能必须找到另一种策略来按喜欢的数量对您的评论进行排序。

Fetching 10 most liked comments, including those without any likes at all (left join) (assuming a simple structure with two tables: comments and likes):

select c.*,count(l.id) as likes
  from comments c 
    left join likes l on c.id = l.comment 
  group by l.comment
  order by count(l.id) desc 
  limit 10;

Note that the performance of this query will be pretty nasty though. Hence you'll most likely have to find another strategy to sort your comments by number of likes.

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