SQL statement to get all customers with no orders

前端 未结 3 1549
甜味超标
甜味超标 2021-02-07 06:14

I have a typical Persons table and an Orders table defined in such a way that I can do JOIN query as the following to return Orders for all Persons.

SELECT Perso         


        
相关标签:
3条回答
  • 2021-02-07 06:44

    You may want to use LEFT JOIN and IS NULL:

    SELECT     Persons.LastName, Persons.FirstName
    FROM       Persons
    LEFT JOIN  Orders ON Persons.id = Orders.Person_id
    WHERE      Orders.Person_id IS NULL;
    

    The result of a left join always contains all records of the "left" table (Persons), even if the join-condition does not find any matching record in the "right" table (Orders). When there is no match, the columns of the "right" table will NULL in the result set.

    0 讨论(0)
  • 2021-02-07 06:55

    Just for completeness, here is the not exists version:

    select * from persons p 
    where not exists
    (select null from orders o where o.person_id = p.id)
    
    0 讨论(0)
  • 2021-02-07 07:01

    This should work... theres more than one way to do it.

    select * from persons where person.id not in (select person_id from orders)
    
    0 讨论(0)
提交回复
热议问题