【问题标题】:Increased count while finding matching recs using left join使用左连接查找匹配记录时增加计数
【发布时间】:2021-06-07 18:25:14
【问题描述】:

我知道这一定是基本的,但出于某种奇怪的原因,当我离开加入我的桌子时,我的计数没有正确。所以基本上 tbl1 有 100 行,tbl2 有 30recs。我正在尝试 tbl1 与 2 以查看有多少记录获得了他们的网站地址。但我的计数远远超过 100,这是我最左边的桌子。我什至在加入时在 tbl2 上使用了 distinct,但它没有帮助。

tbl1

id, name, url, data1

tbl2

id,data3,data4,data5,data6,data6,website

tbl2 包含 tbl1 中缺少的记录的网站数据,因此我正在尝试映射这些以使表格正确。

我的查询

select 
    t1.id, t1.name,
    coalesce(t1.url, t2.website) as url, t1.data1 
from 
    tbl1 
left join 
    (select disctinct id, website 
     from tbl2) t2 on t1.id = t2.id

我总共得到了 110 行,理想情况下我应该只得到 100 行。专家是否可以在这里做出任何假设,看看我为什么会得到它,或者我应该倾注更多数据?

谢谢。

【问题讨论】:

  • 您必须在 t2 中有一些具有重复 ID 的行。 select Id from T2 group by Id having count(*)>1
  • 您确定您的 id 在第二张桌子上是唯一的吗?
  • @Dri372 不!这就是我使用 distinct 的原因。
  • 您不只选择distinct ID - 您正在选择不同的 ID 网站 - 这不是一回事
  • @Stu 你说的太对了!!我的印象是 DISTINCT 会扼杀那些重复的。 (我知道错过这个我很傻)谢谢你,伙计。如果您可以将此评论作为答案,我可以批准。

标签: sql sql-server tsql


【解决方案1】:

您的 outer join 匹配多个 ID 值。

要查找重复的 ID 行,您可以这样做

select *
from T2
where Id in (select Id from T2 group by Id having count(*)>1)

要在示例查询中获得 1:1 连接,您需要通过 Id 使用 group 并在 website 列上使用聚合,或者如果您有其他区分方式,则使用 top (1) 子句,例如Createdate 列等

例如

left join (select Id, max(website) from tbl2 group by Id)

【讨论】:

    【解决方案2】:

    tbl2 包含 tbl1 中缺少的记录的网站数据,所以我正在尝试映射这些以使表格正确。

    那么我们并不真正关心记录处理连接多次,因为您正在寻找连接零次的记录:

    select * 
    from
      tbl1
      left join tbl2 on tbl1.id = tbl2.id
    where
      tbl2.id is null
    

    或者

    select * 
    from
      tbl1 x
    where
      NOT EXISTS(select null from tbl2 y where x.id = y.id)
    

    它会给你所有没有匹配 tbl2 行的 tbl1 行

    如果您想使用它们来修补 tbl2,您可以:

    insert into tbl2(some,columns,here)
    select columns,for,table2
    from
      tbl1 x
    where
      NOT EXISTS(select null from tbl2 y where x.id = y.id)
    

    【讨论】:

      【解决方案3】:

      试试这个:

      SELECT DISTINCT
              t1.id
          ,   t1.name
          ,   url =   COALESCE(t1.url, t2.website)
          ,   t1.data1 
      FROM        tbl1    T1 
      LEFT JOIN   tbl2    T2  ON  T2.id = T1.id
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-07-08
        • 1970-01-01
        • 1970-01-01
        • 2014-02-07
        • 1970-01-01
        • 2023-03-07
        • 1970-01-01
        相关资源
        最近更新 更多