How do you do SQL query for the following condition? Suppose you have two tables: table1 and table2, where each entry in table1 can have multiple corresponding entries in table2. The pseudo code for the query that I want is:
for each $row in table1
$rows = find all rows in table2 that corresponds to $row with $row.id == table2.foreign_id
# $rows is an array of corresponding row in table2
if all rows in $rows meet some condition
then
return $row
else
continue
end
end
EDIT: note in the above pseudo code, I only want the row in table1 that has all its relations in TABLE2 that meets some conditions, not just some condition in table1.
PS: I want to do it in SQL due to efficiency problems that I may have otherwise.
Thanks a lot.
You can reformulate this with a
where not exists ( .. )type clause.For example, pretending you want a list of customers whose orders are all completed:
So you are asking for all customers who have no uncompleted orders – which is the same thing as all customers whose orders are all completed.
Instead of:
You are saying:
Edit: As pointed out in the comments, this will also return customers who have no orders. You could add
and exists (select * from orders where customerid=c.id)to the end of the above to exclude these rows.