1

I need to link the article tables and tags. I created 3 tables

create table Articles (
  Id serial primary key,
  Title char(64),
  Descriptions text
);

create table Tags (
  Id serial primary key,
  Name char(64)
);

create table ArticlesTags (
  ArticleId integer not null references Articles(Id),
  TagId integer not null references Tags(Id)
);

How can I now correctly formulate a sql-request to receive an article and all the tags to it?

3
  • A simple JOIN query. Please post your code, your data set and your wished result set Commented Jul 19, 2018 at 13:33
  • Please remove one of two tags, postgres or mysql Commented Jul 19, 2018 at 13:33
  • I think it's PostreSQL. Removing MySQL tag. Commented Jul 19, 2018 at 13:51

2 Answers 2

3

Join the three tables:

SELECT a.title,
       array_agg(t.name) FILTER (WHERE t.name IS NOT NULL) AS tags
FROM articles a
   LEFT JOIN articlestags at ON a.id = at.articleid
   LEFT JOIN tags t ON at.tagid = t.id
WHERE a.title = 'whatever'
GROUP BY a.title;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, works, and how to make that tags were output by an array?
2

As a slight variation on the answer by @Laurenz (+1), we can use left joins in case a given article might not even have any tags listed:

SELECT a.Title, COALESCE(t.Name, 'NA') AS tag_name
FROM Articles a
LEFT JOIN ArticlesTags at
    ON a.Id = at.ArticleId
LEFT JOIN Tags t
    ON at.TagId = t.Id
WHERE
    a.Title = 'some title';

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.