【发布时间】: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