How to exclude rows that don't join with another table?

前端 未结 7 744
心在旅途
心在旅途 2020-11-30 16:48

I have two tables, one has primary key other has it as a foreign key.

I want to pull data from the primary table, only if the secondary table does not

相关标签:
7条回答
  • 2020-11-30 17:02

    use a "not exists" left join:

    SELECT p.*
    FROM primary_table p LEFT JOIN second s ON p.ID = s.ID
    WHERE s.ID IS NULL
    
    0 讨论(0)
  • 2020-11-30 17:03

    This was helpful to use in COGNOS because creating a SQL "Not in" statement in Cognos was allowed, but it took too long to run. I had manually coded table A to join to table B in in Cognos as A.key "not in" B.key, but the query was taking too long/not returning results after 5 minutes.

    For anyone else that is looking for a "NOT IN" solution in Cognos, here is what I did. Create a Query that joins table A and B with a LEFT JOIN in Cognos by selecting link type: table A.Key has "0 to N" values in table B, then added a Filter (these correspond to Where Clauses) for: table B.Key is NULL.

    Ran fast and like a charm.

    0 讨论(0)
  • 2020-11-30 17:05
    SELECT P.*
    FROM primary_table P
    LEFT JOIN secondary_table S on P.id = S.p_id
    WHERE S.p_id IS NULL
    
    0 讨论(0)
  • 2020-11-30 17:13

    alt text

    SELECT <select_list> 
    FROM Table_A A
    LEFT JOIN Table_B B
    ON A.Key = B.Key
    WHERE B.Key IS NULL
    

    Full image of join alt text

    From aticle : http://www.codeproject.com/KB/database/Visual_SQL_Joins.aspx

    0 讨论(0)
  • 2020-11-30 17:17

    If you want to select the columns from First Table "which are also present in Second table, then in this case you can also use EXCEPT. In this case, column names can be different as well but data type should be same.

    Example:

    select ID, FName
    from FirstTable
    EXCEPT
    select ID, SName
    from SecondTable
    
    0 讨论(0)
  • 2020-11-30 17:19

    Another solution is:

    SELECT * FROM TABLE1 WHERE id NOT IN (SELECT id FROM TABLE2)
    
    0 讨论(0)
提交回复
热议问题