我有一个名为 post_likes 的表,其中包含以下字段
创建时间基于UTC时区。
我们的业务逻辑是,用户每天可以为帖子添加一次 Like (基于PST时区)。意思是,来自FB的1个 LIKE 和来自Linkedin的1个 LIKE 。
我在申请方有一个条件,可以检查和限制试图在同一天给予的人们。不知何故,有些用户在同一天添加了重复的 LIKES (可能是代码或网络服务器问题。请暂时保留此内容)。
我当前的查询如下,以获取每个帖子的数量
SELECT `id`,
`title`,
Sum(IF(`type` = 'FB_LIKES', like_count, 0)) AS fb_like_counts,
Sum(IF(`type` = 'LINKEDIN_LIKES', like_count, 0)) AS linkedin_like_counts,
Sum(`like_count`) AS total_like_counts
FROM `post_likes`
GROUP BY `title`
ORDER BY `total_like_counts` DESC;
现在,我想获得DISTINCT计数。因为某些帖子在当天有重复的赞。在这里,同一位用户可以喜欢第二天。
注意:对不起,我的英语不好,谢谢你
答案 0 :(得分:1)
您只需要对查询进行一些调整即可从表中选择不同的日期。对于以下解决方案,我添加了一个新的select语句以返回相同的 post_likes 表,但日期不同。这将使我能够在一组过滤后的 post_likes
上运行查询Vue.set( app.market.categories, 0, response.data );
您可以使用以下查询来重新创建架构
SELECT `id`,
`title`,
`user_hash` as liked_user,
Sum(IF(`type` = 'FB_LIKES', like_count, 0)) AS fb_like_counts,
Sum(IF(`type` = 'LINKEDIN_LIKES', like_count, 0)) AS linkedin_like_counts,
Sum(`like_count`) AS total_like_counts
FROM (SELECT * FROM post_likes GROUP BY DATE_FORMAT(`created_date`, '%m %d %Y'), user_hash, type) AS post_likes
GROUP BY `title`, DATE_FORMAT(`created_date`, '%m %d %Y'), user_hash
ORDER BY `total_like_counts` DESC;
答案 1 :(得分:0)
下面说的是可能的表结构
INSERT INTO `post_likes` (`id`, `title`, `post_id`, `type`, `user_hash`, `like_count`, `created_date`) VALUES
(1, 'A', 1, 'FB_LIKES', 'ABC', 1, '2018-06-25 05:49:41'),
(2, 'A', 1, 'FB_LIKES', 'DEF', 1, '2018-06-25 05:50:01'),
(3, 'A', 1, 'LINKEDIN_LIKES', 'ABC', 1, '2018-06-25 05:50:16'),
(4, 'A', 1, 'LINKEDIN_LIKES', 'DEF', 1, '2018-06-25 05:50:23'),
(5, 'A', 1, 'FB_LIKES', 'ABC', 1, '2018-06-26 05:50:38');
下面是示例数据:
SELECT `id`, `title`, Sum(IF(`type` = 'FB_LIKES', like_count, 0)) AS fb_like_counts, Sum(IF(`type` = 'LINKEDIN_LIKES', like_count, 0)) AS linkedin_like_counts, Sum(`like_count`) AS total_like_counts, DATE_FORMAT(`created_date`, '%Y-%m-%d') AS `liked_date`
FROM `post_likes`
GROUP BY `title`, `liked_date`
ORDER BY `total_like_counts` DESC;
考虑到您在表中没有任何重复的记录,因此带有日期的查询在此处具有每天的唯一记录:
outerHTML
答案 2 :(得分:0)
抱歉,更新晚了。下面是我的最终查询,给出了正确的结果
SELECT `id`,
`title`,
Sum(IF(`type` = 'FB_LIKES', like_count, 0)) AS fb_like_counts,
Sum(IF(`type` = 'LINKEDIN_LIKES', like_count, 0)) AS linkedin_like_counts,
Sum(`like_count`) AS
total_like_counts FROM (SELECT *,
Date_format(Convert_tz(created_at, '+00:00', '-8:00'), '%Y-%m-%d'
) AS date_pst
FROM `post_likes`
GROUP BY type,
title,
date_pst,
uid_hash) AS D1
GROUP BY `title`
ORDER BY `total_like_counts` DESC;