Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL statement to get all customers with no orders

Tags:

sql

join

mysql

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 Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
INNER JOIN Orders
ON Persons.id=Orders.Person_id

The question is, how do I write a statement that would return all Persons with NO Orders?

I'm using mysql.

Thank all in advance.

like image 780
timeon Avatar asked Oct 04 '10 23:10

timeon


People also ask

How do I find the number of orders in SQL?

The first step is to use the GROUP BY clause to create the groups (in our example, we group by the country column). Then, in the ORDER BY clause, you use the aggregate function COUNT, which counts the number of values in the column of your choice; in our example, we count distinct IDs with COUNT(id) .

What SQL statement is used to get all the rows in a table?

The SQL SELECT statement is used to retrieve records from one or more tables in your SQL database.

In what order are SQL results returned if there is no ORDER BY clause?

If you don't specify an ORDER BY , then there is NO ORDER defined. The results can be returned in an arbitrary order - and that might change over time, too.


1 Answers

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.

like image 173
Daniel Vassallo Avatar answered Oct 02 '22 20:10

Daniel Vassallo