I have two MySQL tables:
CREATE TABLE things (
  id INT
);
CREATE TABLE properties (
  thing_id INT,
  name VARCHAR(100),
  value VARCHAR(100)
);
INSERT INTO things (id) VALUES (1);
INSERT INTO properties (thing_id, name, value) VALUES
  (1, 'name', 'John'),
  (1, 'age', '123');
I want to be able to select properties for a thing based on their names, and return NULL if such a property doesn't exist. Here is what I have attempted:
SELECT
  p1.value AS name,
  p2.value AS age,
  p3.value AS foo
FROM
  things AS t
  LEFT JOIN properties AS p1 ON t.id = p1.thing_id
  LEFT JOIN properties AS p2 ON t.id = p2.thing_id
  LEFT JOIN properties AS p3 ON t.id = p3.thing_id
WHERE
  t.id = 1
  AND p1.name = 'name'
  AND p2.name = 'age'
  AND p3.name = 'foo';
I wanted the result to be
  name |   age | foo
---------------------
'John' | '123' | NULL
But unfortunately this query returns an empty result set, because I think such a p3 doesn't exist.
How can I write a query to do what I want? (And preferably without using explicit LEFT JOINs but commas and WHERE conditions instead, because this is a programmatically generated SQL query.) Thanks for any suggestions.
 
     
     
    