【问题标题】:Select Data in SQL from No links between another table/column从 No links between another table/column 中选择 SQL 中的数据
【发布时间】:2014-01-24 18:34:56
【问题描述】:

有问题的表和(列)是:

Attachment (att_id)

Assignment (att_id, ctg_id, and itm_id)

我已经尝试了几个小时来尝试调用我正在寻找的数据,但没有用。我想不通它背后的逻辑,看起来很简单。

我需要调用附件表中 att_id 链接到分配表中的 ctg_id itm_id 的所有行。

我在 att_id = att_id 上进行连接,但是当我需要相反的情况时,这会显示附件表中 链接到 ctg_id 或 itm_id 的所有行。

非常令人沮丧。非常感谢任何建议/帮助。

【问题讨论】:

    标签: sql sql-server-2008 select join


    【解决方案1】:

    这应该选择 Attachment 中所有未在 Assignment 中被 att_id 引用的行。

    SELECT *
    FROM Attachment
    WHERE att_id NOT IN (SELECT att_id FROM Assignment)
    

    JOIN 通常用于查找链接,而不是查找非链接。 WHERE x NOT IN ([blah]) 用于查找丢失的链接。

    【讨论】:

    • 哇,现在我感到很无助!如所描述的那样工作。我想我想反过来做!感谢它背后的逻辑,我会注意未来。
    【解决方案2】:

    LEFT OUTER JOIN 是查找不匹配项的简单方法:

    select at.*
    from Attachment at
    left outer join Assignment as on at.att_id = as.att_id
    where as.att_id is null
    

    【讨论】:

    • 这也很有效!感谢您向我展示了执行此调用的不同方式背后的更多逻辑!
    【解决方案3】:

    你想要的是Left Anti Semi Join

    SELECT *
    FROM Attachment
    WHERE NOT EXISTS (SELECT 1
                      FROM Assignment
                      WHERE Attachment.att_id = Assignment.att_id)
    

    它也比使用常规的左外连接更有效,尽管 SQL 服务器通常足够聪明,可以解决这个问题。

    【讨论】:

      【解决方案4】:
      select * from attachment a 
      left join assignment a2
      where a2.ctg_id is null or a2.itm_id is null
      

      【讨论】:

        【解决方案5】:

        您可能想尝试另一种方法,以免相关子查询拖慢您的速度。

        create table Attachment (att_id int)
        create table Assignment ( att_id int, ctg_id int, itm_id int)
        insert into Attachment values( 100)
        insert into Attachment values( 350)
        insert into Attachment values( 7)
        insert into Attachment values( 99)
        
        insert into Assignment values ( 100,1,1)
        insert into Assignment values ( 7,2,2)
        
        --SELECT *
        --FROM Attachment
        --WHERE att_id NOT IN (SELECT att_id FROM Assignment)
        
        SELECT ATT.*
        FROM Attachment ATT LEFT outer join Assignment ASI on ATT.att_id = ASI.att_id
        WHERE ISNULL(ASI.att_id,-1)=-1
        
        drop table Attachment
        drop table assignment
        

        编辑:哈哈——当我输入这个时,又有两个相同的答案进来了。哦,好吧。

        【讨论】:

          猜你喜欢
          • 2017-05-29
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多