【问题标题】:How to remove duplicates in a sql JOIN while getting multiple rows from multiple tables如何在从多个表中获取多行的同时删除 sql JOIN 中的重复项
【发布时间】:2020-02-26 00:10:25
【问题描述】:

我的项目是关于一个博客,人们在该博客上发布文章并根据上周的发布范围和广告等每周获得奖励...

对于某种情况,我需要一个从三个表中返回多行的查询,问题是当我使用 JOIN 时有多个重复项,我似乎找不到删除它们的解决方案。

表格的结构如下:

表 1:用户

  ID      | Name      | Age

  1       | Mark      | 16
  2       | Michael   | 21

表 2:帖子

 userID      | postID   | Title

     1       | A1       | Inflation : A simplified Approach
     1       | A2       | The "un-winnable" game of politics
     2       | A3       | What is Bourgeoisie ?
     2       | A4       | The radical views of Carl Marx
     2       | A5       | Anna Karenina, or the greatest novel in history

表 3:收入

   userID     | weekRevenue  

      1       | $0.2    
      1       | $0.14       
      1       | $0.91 
      1       | $1.72 
      2       | $0.99 

我想要的只是一个返回以下内容的查询:

 ID    | postID    | weekRevenue

 1     | A1        | $0.2
 1     | A2        | $0.14
 1     | 'Null'    | $0.91
 1     | 'Null'    | $1.72
 2     | A3        | $0.99
 2     | A4        | 'Null'
 2     | A5        | 'Null'

即: 从所有表中返回值,不复制任何值,也不将两个表中的任何字段链接到Users 表中的ID 字段

这可能吗? ,如果没有,达到我所要求的任何东西的方法是什么?

我的方法(显然失败了)是使用JOIN,这是我的查询

Select A.ID,B.postID,C.weekRevenue
from Users A
left join Posts B
on A.ID=B.userID
left join Revenue C
on A.ID=C.userID;

回报是:

 ID    | postID    | weekRevenue

 1     | A1        | $0.2
 1     | A1        | $0.14
 1     | A1        | $0.91
 1     | A1        | $1.72
 1     | A2        | $0.2
 1     | A2        | $0.14
 1     | A2        | $0.91
 1     | A2        | $1.72
 2     | A3        | $0.99
 2     | A4        | $0.99
 2     | A5        | $0.99

我还尝试了 Right JOINinner 以及它们的组合,返回的表没有显着变化。

任何建议都会有所帮助,非常感谢。

【问题讨论】:

    标签: mysql sql database


    【解决方案1】:

    您不希望结果采用“关系”格式,因为一行中的列彼此之间没有关系。但是,您可以使用row_number()union all 做您想做的事:

    select id, max(postid) as postid, max(weekrevenue) as weekrevenue
    from ((select id, postid, null as weekrevenue,
                  row_number() over (partition by id order by postid) as seqnum
           from posts
          ) union all
          (select id, null as postid, weekrevenue,
                  row_number() over (partition by id order by weekrevenue) as seqnum
           from revenue
          )
         ) pr
    group by id, seqnum;
    

    【讨论】:

      猜你喜欢
      • 2015-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-21
      • 2021-02-05
      • 2023-03-10
      相关资源
      最近更新 更多