tags:

views:

59

answers:

4

Basically I have a main table (accounts) and a meta table (accounts_meta)... The meta table looks like this:

id | account_id | meta_key | meta_value

What I want to do is only select accounts that do not have 'referrer_paid' as a row in the accounts_meta table...

Here is my code so far...

SELECT a.* FROM accounts AS a
    LEFT JOIN accounts_meta AS am ON a.id = am.account_id AND am.meta_key != 'referrer_paid'
    WHERE a.account_referrer != ''
    GROUP BY a.id

Hopefully I am making sense. What am I doing wrong?

A: 

SELECT a.* FROM accounts AS a LEFT JOIN accounts_meta AS am ON a.id = am.account_id AND am.meta_key != 'referrer_paid' WHERE ISNULL(am.account_referrer) GROUP BY a.id

bogdanvursu
you want to check for ISNULL(am.account_id) in where clause instead.
Imre L
yep, thanks for the heads up
bogdanvursu
+3  A: 
SELECT * 
  FROM accounts 
 WHERE id NOT IN ( select DISTINCT account_id 
                     from `account_meta_table` 
                    where meta_key != 'referrer_paid'
                  );
Salil
+1 for avoiding the left join!
lexu
thanx @lexu for proper indenting.
Salil
Left join is faster than subquery in mysql. Might be not so much difference in future when they improve optimizer (ver 6+).
Imre L
+1  A: 
SELECT a.* FROM accounts AS a
LEFT JOIN accounts_meta AS am ON a.id = am.account_id AND am.meta_key = 'referrer_paid'
WHERE a.account_referrer != ''
  AND am.account_id IS NULL

you dont need group by as left-join-is-null don't produce duplicate account rows

EDIT: duh, changed am.meta_key != 'referrer_paid' to am.meta_key = 'referrer_paid'

This is what you wanted. It returns NULL for joined row if it doesnt match and you only take NULL rows

Imre L
+1  A: 

tiny change from @lexu:

SELECT * 
  FROM accounts 
 WHERE id NOT IN ( select account_id 
                     from `account_meta_table` 
                    where meta_key = 'referrer_paid'
                  );
didxga
Thanks lexu and didxga :) Having meta_key = 'referrer_paid' worked instead of the meta_key != 'referrer_paid'. Thank you both!
Ben Sinclair