添加连接后MySQL查询中断

时间:2018-09-20 18:41:17

标签: mysql sql database content-management-system

我有一个查询,该查询为CMS中的循环加载数据以显示帖子。在投票栏中一切正常,直到我离开评论栏。注释显示为“ OK”,但总票数,上票数和下票数却大为不同。让我知道是否需要查看表格。

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

2 个答案:

答案 0 :(得分:0)

您有多个评论。因此,在加入之前先进行汇总:

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有一个很好的简写形式,用于计算布尔表达式为真的次数。

答案 1 :(得分:0)

似乎您决定加入表格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