【问题标题】:Getting table rows in order of sum of count of two another columns from another table按另一个表中另外两个列的计数总和的顺序获取表行
【发布时间】:2015-12-14 07:30:56
【问题描述】:

我有 3 个 MYSQL 表,它们是:

发布

mysql> DESCRIBE `posts`;
+------------------+------------------+------+-----+---------+----------------+
| Field            | Type             | Null | Key | Default | Extra          |
+------------------+------------------+------+-----+---------+----------------+
| post_id          | int(11) unsigned | NO   | PRI | NULL    | auto_increment |
| post_details     | varchar(11)      | NO   |     | NULL    |                |                |
+------------------+------------------+------+-----+---------+----------------+

喜欢

mysql> DESCRIBE `likes`;
+------------------+------------------+------+-----+---------+----------------+
| Field            | Type             | Null | Key | Default | Extra          |
+------------------+------------------+------+-----+---------+----------------+
| id               | int(11) unsigned | NO   | PRI | NULL    | auto_increment |
| post_id          | int(11)          | NO   |     | NULL    |                |
| user_id          | int(11)          | NO   |     | NULL    |                |                |
+------------------+------------------+------+-----+---------+----------------+

评论

mysql> DESCRIBE `comments`;
+------------------+------------------+------+-----+---------+----------------+
| Field            | Type             | Null | Key | Default | Extra          |
+------------------+------------------+------+-----+---------+----------------+
| id               | int(11) unsigned | NO   | PRI | NULL    | auto_increment |
| post_id          | int(11)          | NO   |     | NULL    |                |
| user_id          | int(11)          | NO   |     | NULL    |                |                |
+------------------+------------------+------+-----+---------+----------------+

在第 2 和第 3 表中,我正在存储帖子的喜欢和 cmets(第 1 表)。 现在,我想按喜欢和 cmets 的总和的降序获取帖子。即,帖子将按照最大点赞数 + cmets 到最小数量的顺序排列。 请帮助我获得正确的结果并提前感谢。

【问题讨论】:

    标签: mysql


    【解决方案1】:
    SELECT posts.post_id, post_details,
        ((SELECT(COUNT(id) FROM comments WHERE comments.post_id = posts.post_id)) + (SELECT(COUNT(id) FROM likes WHERE likes.post_id = posts.post_id))) AS weight
    FROM posts
    ORDER BY weight DESC
    

    不使用变量,您可以使用嵌套选择

    【讨论】:

    • 是的,用额外的括号纠正一点语法错误,它开始工作。感谢您的帮助。
    【解决方案2】:

    试试:

    @likes = SELECT COUNT(id) FROM likes;
    @comments = SELECT COUNT(id) FROM comments;
    SELECT post_id, (@likes + @comments) AS TotalStats  FROM posts GROUP BY post_id ORDER BY TotalStats DESC;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-23
      • 2017-07-07
      • 1970-01-01
      相关资源
      最近更新 更多