按照另一个表

时间:2015-12-14 07:30:56

标签: mysql

我有3个MYSQL表:

POST

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表中,我存储了帖子的喜欢和评论(第1张表)。 现在,我希望以喜欢和评论数量的总和的降序来获取帖子。即帖子将按最大数量的喜欢+评论到最小数量。 请帮助我获得正确的结果,并提前感谢。

2 个答案:

答案 0 :(得分:1)

splice

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

答案 1 :(得分:0)

尝试:

@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;