【问题标题】:Duplicate row after left join左连接后重复行
【发布时间】:2017-03-01 03:07:59
【问题描述】:

我正在尝试编写如下查询:

select distinct  bsg.id as bsgId,
s.system_id as sysId,
g.code_no as gameNo,
u.user_name as nameOfUser,
s.score_code as scoreId,
p.name as cityOfGame

from score s
join scoreGr sg on sg.id = s.scoreGr_id
join bigScoreGr bsg on sg.bigScoreGr_id = bsg.id
join game g on bsg.fld_case_id = g.id
join user u on s.user_id = u.id
join system_number sn on g.id = sn.game_id
join system_doc sd on sd.system_number_id = sn.id
left join parameter p on sd.city_id = p.id

直到我加入参数表,结果如预期。结果如下所示:

bsgId| sysId | gameNo | nameOfUser | scoreId
--------------------------------------------------
1234 | abcde | G-12   | admin      | G-12/1/1
1235 | abcdf | G-15   | admin      | G-15/1/3
1234 | abcdf | G-12   | user1      | G-12/1/8
1237 | abcdf | G-16   | user1      | G-16/2/4    

但是,参数表很大,system_doc 在其 city_id 列中有一些空值。当我添加查询的左连接部分时,它变成这样:

bsgId| sysId | gameNo | nameOfUser | scoreId  | city
--------------------------------------------------
1234 | abcde | G-12   | admin      | G-12/1/1 | city1
1235 | abcdf | G-15   | admin      | G-15/1/3 | city5
1235 | abcdf | G-15   | admin      | G-15/1/3 | 
1234 | abcdg | G-12   | user1      | G-12/1/8 | city4
1234 | abcdg | G-12   | user1      | G-12/1/8 | 
1237 | abcdf | G-16   | user1      | G-16/2/4 |

我不想要第三和第五行。为了避免这些行在其城市列中具有空值并且“除了城市字段之外具有完全相同的数据”(我的意思是城市实际上可以为空,就像在最后一行一样,但是具有第 2 行会使第 3 行没用,所以 我只想要第 2 行)我使用了 distinct on(scoreId),但它没有用,因为我丢失了第 2 行但没有丢失第 3 行。

我怎样才能消除那些在他们的城市字段中有 null 的重复行?我希望我的问题很清楚。

【问题讨论】:

  • 据我所知你想要distinct on (bsgId, sysId, gameNo, nameOfUser, scoreId)。不仅仅是distinct on(scoreId)
  • 实际上它们是相同的,因为 scoreId 在您编写的所有字段中都是唯一的。但即便如此,我得到了不希望的结果。此查询有时会消除非空城市,而不是消除具有空城市的行

标签: postgresql duplicates left-join greatest-n-per-group


【解决方案1】:

您似乎有一个复合键。尝试提及复合键的所有列,即如果您有 primary key(pk1, pk2) 然后是 select * from table1 left join table2 on table1.pk1=table2.pk1 and table2.pk2=table2.pk2

【讨论】:

    【解决方案2】:

    这是一个 postgresql 错误。

    在 sd.city_id = p.id 上左连接参数 p

    试试这个

    left join parameter p on p.id = p.id
    WHERE sd.city_id = p.id
    

    (我已经回答了这个问题,所以任何正在寻找的人现在都会知道这个错误)

    【讨论】:

      猜你喜欢
      • 2015-08-02
      • 2017-08-22
      • 1970-01-01
      • 2014-05-11
      • 2011-12-22
      • 2021-12-25
      • 1970-01-01
      • 2016-03-04
      相关资源
      最近更新 更多