2

I'm certain this has been asked and answered already but don't know how exactly the question should be.

I have two tables

ID | name
=========
 1 | foo
 2 | bar
 3 | lou
 4 | sue

and a meta table:

p_ID | key | value
===================
  1  | poo | 1
  2  | zoo | 'whatever'
  3  | clu | 423
  4  | poo | 1

I like to get all entries from the first table which doesn'T have a poo value assigned:

ID | name
=========
 2 | bar
 3 | lou

My approach was

SELECT * 
  FROM table AS p 
  LEFT JOIN meta AS m 
    ON m.p_id = p.ID 
 WHERE m.key = 'poo' 
   AND m.value IS NULL

but this returns an empty result

3 Answers 3

4

You have to move the m.key = 'poo' expression into the ON-clause. Everything that is in the WHERE-clause MUST be present, even in a LEFT JOIN.

SELECT * 
  FROM table AS p 
  LEFT 
  JOIN meta AS m 
    ON m.p_id = p.ID 
   AND m.key = 'poo'
 WHERE m.value IS NULL
Sign up to request clarification or add additional context in comments.

1 Comment

I knew it was that easy!
1

I think you should want this;)

SELECT *
FROM table AS p
LEFT JOIN meta AS m
ON m.p_id = p.ID
AND m.key = 'poo'
WHERE m.value IS NULL

When you use m.key = 'poo' in WHERE clause, this will be computed as INNER JOIN, so you only get records with m.key = 'poo', not all rows in table.

Comments

0

You can use INNER JOIN instead.

SELECT *
    FROM `table` T
    INNER JOIN meta M ON M.p_id = T.ID
    WHERE M.key <> 'poo'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.