【问题标题】:SQL JOIN only one matchSQL JOIN 只有一个匹配
【发布时间】:2021-09-07 08:36:39
【问题描述】:

我们有三个表:podcasts (podcast_id, title)、reviews (podcast_id, rating, review_title, author_id) 和 category (podcast_id, category)。

当我加入这些表时,我会收到两次播客和评论,因为在类别表中,一些 podcast_id 被列出两次,因为它们有两个对应的类别。

事实上,每个播客只需要一个类别,我如何加入表格,从类别表中每个播客只选择一个类别?我需要保留所有评论,所以 GROUP BY podcasts.title 不行。

这是我当前正在运行的查询:

SELECT podcasts.title AS podcast,
categories.category,
reviews.title AS review,
reviews.rating,
reviews.author_id
FROM podcasts
LEFT OUTER JOIN reviews ON reviews.podcast_id = podcasts.podcast_id
LEFT JOIN categories ON categories.podcast_id = podcasts.podcast_id

【问题讨论】:

  • 您当前正在运行的 SQL 查询是什么?
  • 您可以使用 Group by 来消除重复项
  • @Kleo G 选择 podcasts.title 作为播客,category.category,reviews.title 作为评论,reviews.rating,reviews.author_id 从播客 LEFT OUTER JOIN 评论 ON reviews.podcast_id = podcasts.podcast_id LEFT加入类别 ON categories.podcast_id = podcasts.podcast_id
  • @Subhashis Padey 如果我分组,我会错过评论,我想保留所有评论。
  • 如果每个 ID 有 2 个不同的类别,应该显示哪个类别?如果它们相同,只需使用 select distinct。您问题中的示例数据(请参阅Minimal, Reproducible Example)会有所帮助。

标签: sql


【解决方案1】:

那么你想扔掉哪个类别?如果你不在乎,你可以使用这个:

SELECT podcasts.title AS podcast,
C.category,
reviews.title AS review,
reviews.rating,
reviews.author_id
FROM podcasts
LEFT OUTER JOIN reviews ON reviews.podcast_id = podcasts.podcast_id
LEFT JOIN (
     select podcast_id, MAX(category) as category 
     from  categories 
     group by podcast_id
     ) C
 ON C.podcast_id = podcasts.podcast_id

【讨论】:

  • MAX 选择最后一个,MIN 选择第一个。是否可以选择名称最短的类别?
  • 我自己找到了答案:LEFT JOIN ( select podcast_id, category from categories group by podcast_id HAVING LENGTH(category) = MIN(LENGTH(category)) ) C
  • 这就是为什么在原始问题中预先解释整个情况很重要的原因。当两个类别的最小长度相同时,您是否测试过您的解决方案?
  • 可能没有类别名称具有相同长度的情况,因为我使用MAX(category) as category 解决方案和MIN(LENGTH(category)) 解决方案获得了相同数量的行。另一方面,在这两种情况下,我都在数据框中找到了一些重复的 reviews[reviews[['podcast','review','rating','author_id']].duplicated(keep=False)]
  • 无论如何,MAX 解决方案始终有效。如果您将来有两个长度相同的类别,则 min(length(category)) 解决方案将导致重复。我建议立即删除此错误,而不是让它在将来随机给您带来问题。
【解决方案2】:

如果您有两个具有相同值的条目,则使用 distinct 关键字,这将帮助您消除另一个条目。

【讨论】:

    猜你喜欢
    • 2022-01-01
    • 2019-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    • 1970-01-01
    • 2017-10-16
    相关资源
    最近更新 更多