mysql查询中断

ui7jx7zq  于 2021-06-19  发布在  Mysql
关注(0)|答案(2)|浏览(416)

我有一个查询,在我的cms中加载一个循环的数据来显示帖子。投票栏一切都很好,直到我离开加入评论栏。评论显示正常,但是totalvote、upvote和downvote的计数非常不一致。如果你需要看table,请告诉我。

SELECT
count(DISTINCT comment.comment ) AS Comment,
idea.dateofcreation AS timestamp, 
idea.userId AS userId,
idea.id AS ID,
idea.text AS Idea,
page.permalink AS Permalink,
user.name AS Username,
COUNT(CASE WHEN votelog.vote !="" THEN 1 END) AS 'totalvotes',
COUNT(CASE WHEN votelog.vote = '1' THEN 1 END) AS 'upvote',
COUNT(CASE WHEN votelog.vote = '-1' THEN 1 END) AS 'downvote'
FROM idea
LEFT JOIN votelog ON idea.id = votelog.ideaid
LEFT JOIN user ON idea.userId = user.id
LEFT JOIN page ON idea.id = page.ideaid
LEFT join comment ON comment.ideaid = idea.id 
GROUP BY idea.id
ORDER BY totalvotes DESC
bkhjykvo

bkhjykvo1#

您有多条评论。因此,在加入之前:

SELECT c.num_comments,
       i.dateofcreation AS timestamp, i.userId AS userId, i.id AS ID, i.text AS Idea,
       p.permalink AS Permalink, p.name AS Username,
       SUM( vl.vote <> '' ) AS totalvotes,
       SUM( vl.vote = 1 ) AS upvote,
       SUM( vl.vote = -1 ) AS downvote
FROM idea i LEFT JOIN
     votelog vl
     ON i.id = vl.ideaid LEFT JOIN
     user u
     ON i.userId = u.id LEFT JOIN
     page p
     ON i.id = p.ideaid LEFT JOIN
     (SELECT c.ideaid, COUNT(*) as num_comments
      FROM comment c
      GROUP BY c.ideaid
     ) c
     ON c.ideaid = i.id 
GROUP BY c.num_comments,
       i.dateofcreation i.userId, i.id, i.text,
       p.permalink, p.name
ORDER BY totalvotes DESC;

笔记:
表别名使查询更易于编写和读取。
将所有未聚合的列包含在 GROUP BY (mysql的最新版本倾向于强制执行这一点)。
我猜选票是数字。把它们比作数字,而不是字符串。
mysql有一个很好的计算布尔表达式为真的次数的速记。

z5btuh9x

z5btuh9x2#

看来你决定加入这一行列了 comments 只数有多少评论。
但是通过这样做,您现在可以生成多个行,每个注解一行,这样就可以取消所有其他行的计数。
我建议使用标量子查询来统计注解,并删除连接。比如:

SELECT
(select count(DISTINCT comment) from comment c where c.ideaid = idea.id) AS Comment,
idea.dateofcreation AS timestamp, 
idea.userId AS userId,
idea.id AS ID,
idea.text AS Idea,
page.permalink AS Permalink,
user.name AS Username,
COUNT(CASE WHEN votelog.vote !="" THEN 1 END) AS 'totalvotes',
COUNT(CASE WHEN votelog.vote = '1' THEN 1 END) AS 'upvote',
COUNT(CASE WHEN votelog.vote = '-1' THEN 1 END) AS 'downvote'
FROM idea
LEFT JOIN votelog ON idea.id = votelog.ideaid
LEFT JOIN user ON idea.userId = user.id
LEFT JOIN page ON idea.id = page.ideaid
GROUP BY idea.id
ORDER BY totalvotes DESC

相关问题