views:

27

answers:

3

I have a Users table and a Payments table. I need a query which lists the users who DO NOT have a record in the payments table where the field PaymentCompleted=1.

These are the columns in the tables (simplified):

     Users: UserID, UserName
  Payments: PaymentID, UserID, PaymentCompleted

The query should select the field UserName.

+2  A: 
  SELECT UserName
  FROM Users u
  WHERE NOT EXISTS(Select 1 
                   from Payments p 
                   Where p.UserId = u.UserId
                   AND p.PaymentCompleted = 1)
Michael Pakhantsov
damn you were 7 seconds quicker :)
Nicolas78
+2  A: 
select distinct UserName
from Users left outer join Payments on Users.UserID = Payments.UserID
where PaymentCompleted is NULL or PaymentCompleted != 1
Dan Breen
+1 high performance
Wadih M.
This doesn't quite work as one user could have a payment record with PaymentCompleted = 1 and another with PaymentCompleted = 0.
ar
@ar: Good point, this is not a proper solution. It may work in OP's situation depending on the logic of how payments get added. The query will, however, return all users that either don't have a Payment or don't have a completed Payment (regardless of also potentially having completed payments). This may or may not be what he was looking for, though not exactly what he asked.
Dan Breen
A: 

select * from t_users T where T.userid not exists (select p.userid from t_payments t where PaymentCompleted=1).

One note: "not in" clauses can be computationally inefficient for large numbers of records. If you start seeing performance issues, you may want to do some refactoring/redesign.

Jason
Please use the code formatting.
ar