我有一个mysql选择获取帖子,喜欢它,评论。 问题是我注意到,如果一个帖子有2个像或更多,它将乘以评论数。
例如:用户有2条评论。
1 like - 2 comment
2 likes - 4 comments (user has 2, but will show 4)
3 likes - 6 comments (user has 2)
可以看出喜欢是以某种方式增加评论。
我的查询有什么问题?
select c.nome, p.foto, c.user, p.user, p.id, p.data, p.titulo, p.youtube, pp.foto, count(DISTINCT likes.user) as likes_count, SUM(CASE comentarios.delete WHEN 0 THEN 1 ELSE 0 END)
as comentarios_count, count(DISTINCT l2.user) as count2 from posts p
join cadastro c on p.user=c.id
left join profile_picture pp on p.user = pp.user
left join likes on likes.post = p.id // here?
left join comentarios on comentarios.foto = p.id
left join likes l2 on l2.post = p.id and l2.user = '1'
group by p.id
order by p.id desc limit 10
CREATE TABLE IF NOT EXISTS `likes` (
`user` int(11) UNSIGNED NOT NULL,
`post` int(11) UNSIGNED NOT NULL,
`data` datetime NOT NULL,
UNIQUE KEY `user_post` (`user`,`post`),
FOREIGN KEY (`post`) REFERENCES posts (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `comentarios` (
`id` int(11) UNSIGNED NOT NULL AUTO_INCREMENT,
`foto` int(11) UNSIGNED NOT NULL,
`user` int(11) UNSIGNED NOT NULL,
`texto` varchar(3000) NOT NULL,
`data` datetime NOT NULL,
`ip` varchar(20) NOT NULL,
`delete` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`),
FOREIGN KEY (`foto`) REFERENCES posts (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 AUTO_INCREMENT=1 ;
如果需要另一张桌子,请问。
答案 0 :(得分:1)
你必须得到喜欢,用不同的查询评论。因为你已经加入了他们,但他们彼此没有相互关联,喜欢和评论属于post,所以你创建了一个查询,让帖子喜欢和评论查询不要在数据库级别混合,你必须管理通过代码,您可以使用每个喜欢的更新查询管理邮政表上的计数器,并根据需要进行评论。希望你明白我的意思......