【问题标题】:Left Joins that link to multiple rows only returning one链接到多行的左连接只返回一个
【发布时间】:2010-12-26 13:50:37
【问题描述】:

我正在尝试加入两个表(称它们为 table1 和 table2),但每次匹配只返回 1 个条目。在 table2 中,有一个名为“current”的列,它可以是“y”、“n”或“null”。我已经离开加入了这两个表,并放置了一个 where 子句来让我得到 'y' 和 'null' 实例,这些很容易。我需要帮助来获取加入仅具有“n”的行以返回“none”或“null”的一个实例的行。这是一个例子

表1 身份证
1
2
3

表2
身份证 |表1ID |当前
1 | 1 |是的
2 | 2 |空
3 | 3 | n
4 | 3 | n
5 | 3 | n

我当前的查询在 table1.ID=table2.table1ID 上加入,然后有一个 where 子句(其中 table2.current = 'y' 或 table2.current = 'null')但是当没有 ' y' 并且值不是 'null'。

有人能想出一个查询,像我一样加入表,但像这样从 table1 中获取所有 3 条记录吗?

查询返回

ID |表2ID |当前
1 | 1 |是的
2 |空 |空
3 | 3 |为空或无

【问题讨论】:

    标签: join outer-join


    【解决方案1】:

    您需要决定 table2 中 table1id = 3 的三行中的哪一行:

    3 | 3 | n
    4 | 3 | n
    5 | 3 | n
    

    标准是什么?

    【讨论】:

    • 我实际上并不想要它们,我只需要知道没有'y'或空值,是的,那是DB空值,而不是字符串值。
    【解决方案2】:

    首先,我假设“null”值实际上是字符串,而不是 DB 值 NULL。 如果是这样,下面的这个查询应该可以工作(注意在 ON 子句中包含 where 条件)

    select 
    table1.ID as ID
    ,table2.ID as table2ID
    ,table2.current 
    from table1 left outer join table2 
    on (table2.table1ID = table1.ID and 
    (table2.current in ('y','null'))
    

    如果这确实有效,我强烈建议将“null”字符串值更改为其他值,因为它完全具有误导性……您或其他开发人员将来会浪费时间调试它。

    如果“null”实际上指的是空值,则将上述查询更改为:

    select 
    table1.ID as ID
    ,table2.ID as table2ID
    ,table2.current 
    from table1 left outer join table2 
    on (table2.table1ID = table1.ID and 
    (table2.current = 'y' or table2.current is null))
    

    【讨论】:

    • 我要试试这个,我说的空值是我离开join时返回的,table2中没有那个特定的行
    • 这不会返回 table1 ID 3 的值,因为它没有“y”或不为空
    【解决方案3】:
    select t1.id
         , t2.id
         , case when t2.count_current > 0 then
               t2.count_current 
           else
               null
           end as current
    from table1 t1
    left outer join
    (
      select id
      , max(table1id)
      , sum(case when current = 'y' then 1 else 0 end) as count_current
      from table2
      group by id
    ) t2
    on t1.id = t2.table1id
    

    尽管正如刚才有人指出的那样,一旦您的表 2 中有多行带有“y”的行,这可能不会像您预期的那样工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-20
      • 1970-01-01
      相关资源
      最近更新 更多