gpt4 book ai didi

mysql - 我怎样才能计算帖子的数量?

转载 作者:太空宇宙 更新时间:2023-11-03 10:37:20 25 4
gpt4 key购买 nike

这是我的表结构:

-- reputations
+----+-------------+---------+-------+------------+------------+
| id | post_id | user_id | score | reputation | date_time |
+----+-------------+---------+-------+------------+------------+ -- Suppose:
| 1 | 1 | 1 | 1 | 5 | 1500489844 | -- out of last week
| 2 | 4 | 3 | -1 | -2 | 1500499815 | -- out of last week
| 3 | 2 | 3 | 1 | 5 | 1500584821 |
| 4 | 3 | 1 | 1 | 5 | 1501389166 |
| 5 | 2 | 4 | 1 | 5 | 1501399142 |
| 6 | 2 | 1 | -1 | -2 | 1501399142 |
| 7 | 4 | 1 | 0 | 15 | 1501481186 |
| 8 | 5 | 1 | 1 | 5 | 1501481297 |
+----+-------------+---------+-------+------------+------------+
-- Note: the last row came from an accepted-answer, that's why its score is 0

-- post_tag
+---------+--------+
| post_id | tag_id |
+---------+--------+
| 1 | 2 |
| 1 | 4 |
| 2 | 2 |
| 3 | 1 |
| 3 | 4 |
| 4 | 3 |
| 5 | 1 |
+---------+--------+

-- tags
+----+--------+
| id | name |
+----+--------+
| 1 | php |
| 2 | html |
| 3 | css |
| 4 | mysql |
+----+--------+

这是我的查询:

SELECT
t.tag, sum(r.reputation) AS tag_reputation, sum(r.score) AS tag_score
FROM
users u
LEFT JOIN reputations r
ON r.user_id = u.id
AND r.date_time > 1500584821
JOIN post_tag pt ON pt.post_id = r.post_id
JOIN tags t ON t.id = pt.tag_id
WHERE u.id = 1 -- Specific user: Jack
GROUP BY
u.id, u.user_name, t.tag
ORDER BY
u.id, tag_reputation DESC;

这是当前的结果:

tag   | tag_reputation |  tag_score
----: | :------------- | :---------
css | 15 | 0
php | 10 | 2
mysql | 5 | 1
html | -2 | -1

如您所见,结果是一个标签列表,其中包含按 tag_reputation 排序的特定用户的声誉和分数。 <强> Fiddle


现在我还想计算每个标签的帖子数。所以这是预期的结果:

tag   | tag_reputation |  tag_score | post_num
----: | :------------- | :--------- | :-------
css | 15 | 0 | 1
php | 10 | 2 | 2
mysql | 5 | 1 | 1
html | -2 | -1 | 1

我该怎么做?我想我必须处理 post_id 列和 GROUP BY 子句。但我不知 Prop 体如何。

最佳答案

您是否尝试将帖子 ID 添加到查询中?

我在您的select 语句中添加了count(r.post_id) as post_num 并且它gave the expected results .

要删除重复项,请使用 distinct。你想要关于标签表的计数吗?尝试

  1. COUNT(distinct pt.post_id) AS post_count;或
  2. COUNT(distinct r.post_id) AS post_count

关于mysql - 我怎样才能计算帖子的数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45767611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com