Opposite of inner join

后端 未结 4 1175
清歌不尽
清歌不尽 2021-01-30 14:16

What will be the opposite of inner join? For a table table Person (int PersonId, varchar PersoName, int AddrId), I want to know the rows in Person with bad Ad

4条回答
  •  孤独总比滥情好
    2021-01-30 14:48

    If you consider an inner join as the rows of two tables that meet a certain condition, then the opposite would be the rows in either table that don't.

    For example the following would select all people with addresses in the address table:

    SELECT p.PersonName, a.Address
    FROM people p
    JOIN addresses a
        ON p.addressId = a.addressId
    

    I imagine the "opposite" of this would be to select all of the people without addresses and all addresses without people. However this doesn't seem to be what you are asking, you seem to be interested in just one component of this: all the people without an address in the addresses table.

    For this a left join would be best:

    SELECT p.PersonName
    FROM people p
    LEFT JOIN addresses a
       ON p.addressId = a.addressId
    WHERE a.addressId IS NULL
    

    Note that often some prefer to write it differently as in their opinion it is more readable (however in my experience with large tables it performs worse than the above way):

    SELECT PersonName
    FROM people
    WHERE addressId NOT IN (SELECT addressId FROM addresses)
    

提交回复
热议问题