开发者

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

开发者 https://www.devze.com 2023-01-02 10:47 出处:网络
Basically I have a main table (accounts) and a meta table (accounts_meta)... The meta table looks like this:

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 cod开发者_Go百科e 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?


tiny change from @lexu:

SELECT * 
  FROM accounts 
 WHERE id NOT IN ( select account_id 
                     from `account_meta_table` 
                    where meta_key = 'referrer_paid'
                  );


SELECT * 
  FROM accounts 
 WHERE id NOT IN ( select DISTINCT account_id 
                     from `account_meta_table` 
                    where meta_key != 'referrer_paid'
                  );


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消