代码之家  ›  专栏  ›  技术社区  ›  andyk

SQL帮助:计数聚合、条目列表及其注释计数

  •  0
  • andyk  · 技术社区  · 15 年前

    所以,我打算做的是获取一个条目/文章的列表,其中包含它们的类别和用户详细信息,以及它们发布的所有评论。(条目、类别、用户和注释是单独的表)

    下面的查询可以很好地提取记录,但它似乎跳过那些没有注释的条目。据我所见,联接是良好的(在注释表上留下联接),查询是正确的。我错过了什么?

    SELECT entries.entry_id, entries.title, entries.content,
    entries.preview_image, entries.preview_thumbnail, entries.slug,
    entries.view_count, entries.posted_on, entry_categories.title AS category_title,
    entry_categories.slug AS category_slug, entry_categories.parent AS category_parent,
    entry_categories.can_comment AS can_comment, entry_categories.can_rate AS can_rate,
    users.user_id, users.group_id, users.username, users.first_name, users.last_name,
    users.avatar_small, users.avatar_big, users.score AS user_score, 
    COUNT(entry_comments.comment_id) AS comment_count
    
    FROM (entries)
    JOIN entry_categories ON entries.category = entry_categories.category_id
    JOIN users ON entries.user_id = users.user_id
    LEFT JOIN entry_comments ON entries.entry_id = entry_comments.entry_id
    
    WHERE `entries`.`publish` = 'Y'
    AND `entry_comments`.`publish` = 'Y'
    AND `entry_comments`.`deleted_at` IS NULL
    AND `category` = 5
    
    GROUP BY entries.entry_id, entries.title, entries.content,
    entries.preview_image, entries.preview_thumbnail, entries.slug,
    entries.view_count, entries.posted_on, category_title, category_slug,
    category_parent, can_comment, can_rate, users.user_id, users.group_id,
    users.username, users.first_name, users.last_name, users.avatar_big,
    users.avatar_small, user_score
    
    ORDER BY posted_on desc
    

    编辑:我正在使用MySQL5.0

    3 回复  |  直到 15 年前
        1
  •  1
  •   FWH    15 年前

    好吧,你在做一个关于条目注释的左连接,条件是:

    `entry_comments`.`publish` = 'Y'
    `entry_comments`.`deleted_at` IS NULL
    

    对于没有注释的条目,这些条件是错误的。 我想这应该能解决问题:

    WHERE `entries`.`publish` = 'Y'
    AND (
            (`entry_comments`.`publish` = 'Y'
            AND `entry_comments`.`deleted_at` IS NULL)
        OR
            `entry_comments`.`id` IS NULL
        )
    AND `category` = 5
    

    entry_comments . id ,假定这是条目注释表的主键,因此应将其替换为条目注释的实际主键。

        2
  •  1
  •   David M    15 年前

    这是因为您正在对 entry_comments 表。将第一个替换为:

    AND IFNULL(`entry_comments`.`publish`, 'Y') = 'Y'
    

    因为这个表上的另一个筛选器是 IS NULL 第一,这是您所需要做的全部工作,以允许从左联接到的不匹配行。

        3
  •  0
  •   hermiod    15 年前

    尝试将左联接更改为左外部联接

    我不是这种SQL连接的专家(我自己更像是一个甲骨文专家),但是左连接的措词让我相信它正在把entry_comments连接到entry_comments连接到entry_comments连接到entry_左边,你真的希望它是另一种连接方式(我认为)。

    因此,尝试以下方法:

    在entries.entry_id=entry_comments.entry_id上保留外部联接条目