【问题标题】:Why is MySQL COUNT returning double of what I expect when counting joined columns?为什么在计算连接列时 MySQL COUNT 返回的结果是我预期的两倍?
【发布时间】:2018-04-04 20:44:32
【问题描述】:

我正在尝试在 wordpress 中构建用户通知系统。我有一个查询,它连接 wp_posts 表中的行,这些行的 post_status 为发布,post_author 为 1,post_type 为 user_notification。有两行满足这些要求。 total_unread 列始终为 4,整个查询仅返回 1 行。我究竟做错了什么?这是SqlFiddle

这是表结构

CREATE TABLE `wp_posts` (
  `ID` bigint(20),
  `post_author` bigint(20) DEFAULT '0',
  `post_content` longtext NULL,
  `post_status` varchar(20) DEFAULT 'publish',
  `post_type` varchar(20) DEFAULT 'post'
) ENGINE=InnoDB;
INSERT INTO wp_posts
(ID, post_author, post_content, post_status, post_type)
VALUES(1, 1, 'John Smith would like to be friends!', 'publish', 'user_notification');
INSERT INTO wp_posts
(ID, post_author, post_content, post_status, post_type)
VALUES(2, 1, 'Sally Miller shared your post!', 'publish', 'user_notification');

这里是查询:

SELECT SQL_CALC_FOUND_ROWS  wp_posts.ID, wp_posts.post_status, COUNT(unread.post_status) as total_unread 
FROM wp_posts  
 JOIN wp_posts AS unread ON unread.post_author = 1 AND unread.post_status = 'publish' AND unread.post_type = 'user_notification'
WHERE wp_posts.post_author IN (1)  
      AND wp_posts.post_type = 'user_notification' 
ORDER BY wp_posts.ID DESC LIMIT 0, 5

【问题讨论】:

  • Offtopic:您可以从 WHERE 子句中删除 1=1,它总是正确的,而且看起来很笨拙
  • 啊,是的,我不确定 Wordpress 为什么将它添加到他们的 WP_Query 函数中。
  • 您期待什么结果?因为您使用的是没有 GROUP BY 的 COUNT,所以总是产生一条记录。而且您显然想要更多记录,因为您使用的是LIMIT 0, 5..此外,我真的不知道为什么您在该表上使用了自联接..

标签: mysql


【解决方案1】:

问题是您的JOIN 正在创建每个帖子与其他帖子的叉积,因此您的计数为 4 (2x2)。如果表中有 3 行相似的行,则计数为 9。尝试以 SELECT * 而不是当前字段运行查询,您将看到 4 行。

我真的不明白你为什么使用JOIN?你想达到什么目的?如果您只想计算“未读”帖子(由post_status='publish' 表示),则此查询就足够了:

SELECT post_author, SUM(IF(post_status='publish',1,0)) as total_unread 
FROM wp_posts 
WHERE post_type = 'user_notification' 
GROUP BY post_author

甚至更简单:

SELECT post_author, COUNT(*) as total_unread 
FROM wp_posts 
WHERE post_type = 'user_notification' AND post_status='publish'
GROUP BY post_author

【讨论】:

    【解决方案2】:

    我运行了您的SQL Fiddle 添加了另一条记录,即unpublished 以查看结果如何,它仍然使价值翻了一番。

    此外,当使用 JOIN 时,您的查询结构应该更像这样:

    SELECT * FROM wp_posts t1
    JOIN wp_posts t2 ON t1.ID = t2.ID
    WHERE...
    //attempted this in your fiddle and it actually resolves your issue.
    

    由于您的 JOIN 没有这样的关系,这一切都可以通过一个查询来完成。我保留了您的所有参数,因为您可能需要唯一用户的统计信息。您可以在这个SQL Fiddle 中查看结果,我在其中添加了另一个post_author

    这是我使用的查询:

    SELECT post_author, post_status, COUNT(post_author) as total_unread 
    FROM wp_posts 
    WHERE post_type = 'user_notification' 
    AND post_status = 'publish'
    AND post_author = 1
    GROUP BY post_author
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-22
      相关资源
      最近更新 更多