Question

I have a query that returns ALL the appointments for an advisor in a week, and what items they sold at that appointment (if non have been sold it still shows the appointment) I have done this by using a left outer join on the appointments table and ithe items table.

In this scenario I only want to display sold items in stock ( in stock is a field in the items table) If I use a 'where instock true' against items, I loose all the appointments where no items have been sold ? Do I need to nest these queries somehow - if so how ? Thanks

Was it helpful?

Solution

The key to what you want to do is to move the condition on the stock to the on clause from the where clause. Presumably, your existing query looks something like this:

select <whatever>
from appointments a left join
     sells s
     on a.appointmentid = s.appointmentid 
where s.instock = 1;

The where clause is turning the left join into an inner join. When there is no match, the value of instock is NULL, which does not match 1. The solution is to move the condition to the on clause:

select <whatever>
from appointments a left join
     sells s
     on a.appointmentid = s.appointmentid and
        s.instock = 1;

OTHER TIPS

You should use ON instead WHERE. That way, if the items aren't in stock the wont match and the right part of your join will be NULL.

SELECT A.*, S.* FROM appointments A LEFT JOIN sells S ON ... AND sells.instock = 1;

I could be more precise if I had the SQL you've tried to write.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top