Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select rows that don't have value in a second table

Tags:

mysql

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?

like image 288
Ben Sinclair Avatar asked Dec 29 '22 14:12

Ben Sinclair


2 Answers

tiny change from @lexu:

SELECT * 
  FROM accounts 
 WHERE id NOT IN ( select account_id 
                     from `account_meta_table` 
                    where meta_key = 'referrer_paid'
                  );
like image 115
didxga Avatar answered Dec 31 '22 13:12

didxga


SELECT * 
  FROM accounts 
 WHERE id NOT IN ( select DISTINCT account_id 
                     from `account_meta_table` 
                    where meta_key != 'referrer_paid'
                  );
like image 23
Salil Avatar answered Dec 31 '22 12:12

Salil