【问题标题】:Is it possible to consolidate records from a SELECT statement that have duplicate column values with another record in SQL?是否可以将 SELECT 语句中具有重复列值的记录与 SQL 中的另一条记录合并?
【发布时间】:2021-12-22 12:48:22
【问题描述】:

考虑我有以下表格/实体:

Posts

id user_id title content
1 1 Article 1 Lorem ipsum
2 1 Article 1 Lorem ipsum
3 1 Article 2 Lorem ipsum 2
4 2 Article 3 Lorem ipsum

Users

id name
1 John Doe
2 Timothy Fisher

请注意,来自 ID 为 1 的用户的两个帖子具有相同的标题和内容。应用程序级别出现错误,允许用户在过去两次提交帖子,导致“重复”记录。

我希望查询所有帖子,但合并每个用户的帖子,这些帖子具有重复的标题内容。

理想的结果集如下所示:

post_id author_name title content
1 John Doe Article 1 Lorem ipsum
3 John Doe Article 2 Lorem ipsum 2
4 Timothy Fisher Article 3 Lorem ipsum
SELECT
  posts.id as post_id,
  users.name as author_name
  posts.title,
  posts.content
FROM
  posts
INNER JOIN
  users
ON
  posts.user_id = users.id;

查询是否为 John Doe 拉出 12 无关紧要。在实际的数据库中,我有时间戳,所以我很可能只提取最新的。

这可以通过 SQL 实现吗?

【问题讨论】:

    标签: mysql sql database


    【解决方案1】:

    在 MySQL 中,您也可以在没有聚合的情况下执行此操作。但我不确定这是否是一个好习惯(更多信息here + 见评论)。

    SELECT
      posts.id as post_id,
      users.name as author_name,
      posts.title,
      posts.content
    FROM
      posts
    INNER JOIN
      users
    ON
      posts.user_id = users.id
    GROUP BY
      users.name, posts.title, posts.content;
    

    【讨论】:

    • post id 将是任意的,这不是数据库的好行为。此外,在 MySQL 8 中,默认情况下不推荐使用并关闭该功能。这通常是不好的做法,通常是不必要的,而且是一种烂代码的味道。
    【解决方案2】:

    你可以使用一个虚假的聚合函数和分组

    SELECT 
      min(posts.id) as post_id,
      users.name as author_name
      posts.title,
      posts.content
    FROM  posts
    INNER JOIN  users  ON   posts.user_id = users.id
    GROUP BY   users.name, posts.title, posts.content
    

    【讨论】:

    • 我想我什至没有考虑 group by。等等,如果没有聚合功能,这会起作用吗?我可以简单地添加group by posts.title, posts.content,它给了我正确的结果集。
    • 哦,我现在看到 min/max 只是指定要提取哪个 ID,太棒了!比我想象的要容易得多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    相关资源
    最近更新 更多