Relationships, joins and SQL projections
An article card shows a headline and the name of the person who wrote it. Let’s fetch the two together and pass the result to the view.
Read the join in the query
Join the article to its author in the query. Select just the fields your card needs and give each result column the label expected by the Bend record. TypedSQL checks that the column types fit.
Join an article to its author
A foreign key points to a row in another table. Add NOT NULL when that relationship is required. An inner join drops articles with no match. A left join keeps them, so even a right-side column declared NOT NULL can come back as SQL null.
This inner join selects the author’s username for each article it finds.
SELECT a.title, u.username
FROM articles AS a
JOIN users AS u ON u.id = a.author_id;Store who favorited which article
Use a join table with a key on the pair of IDs. A second add for the same pair cannot create another row. To find out whether the current reader added an article, use EXISTS in its projection.
The Journal uses UUIDs for both sides of this pair.
CREATE TABLE article_favorites (
user_id uuid REFERENCES users(id) ON DELETE CASCADE,
article_id uuid REFERENCES articles(id) ON DELETE CASCADE,
PRIMARY KEY (user_id, article_id)
);Give the result column a record field name
Use an alias for the name you want in Bend. The record only needs the columns you select.
SELECT a.title, u.username AS author_name
FROM articles AS a
LEFT JOIN users AS u ON u.id = a.author_id
Here the left join makes author_name nullable. In TypedSQL, that is the value of one column. The whole row can have a separate absence case.