I’ve got three tables:
CREATE TABLE credential_types (
id serial PRIMARY KEY,
name varchar(32) NOT NULL,
...
);
CREATE TABLE credentials (
user_id integer REFERENCES users(id),
credential integer REFERENCES credential_types(id),
UNIQUE (user_id, credential)
);
CREATE TABLE users (
id serial PRIMARY KEY,
name varchar(64),
username varchar(64),
...
);
Now, I want to fetch all users that exist, and I want to fetch the particular credential type they have. I tried this:
ribit=> SELECT u.id, u.name, u.username, ct.name AS cred \
FROM users u, credential_types ct, credentials c \
WHERE c.user_id=u.id AND ct.id=c.credential;
id | name | username | cred
----+------+----------+---------
1 | foo | bos | Try-Out
(1 row)
Which is correct kind of output, but all the users that do not yet have a credential (null) are left out. I do not know which kind of JOIN I need for this operation. I think I need a LEFT JOIN, but I fail hard when I try to achieve what I want:
ribit=> SELECT u.id, u.name, u.username, ct.name \
FROM users u, credential_types ct \
LEFT JOIN credentials c ON ct.id=c.credential;
gives me a cross join with erronious data.
What I’m looking for are hints of how to write the query to produce the output I want.
The left join is not quite in the right place.
I think this is closer to what you want.