如何从Postgres表中获取数据(很多)

时间:2018-07-19 13:31:17

标签: sql postgresql

我需要链接文章表和标签。我创建了3张桌子

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)
);

我现在如何正确地制定一个sql-request来接收文章及其所有标签?

2 个答案:

答案 0 :(得分:3)

加入三个表:

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;

答案 1 :(得分:2)

与@Laurenz(+1)的回答略有不同,我们可以使用左联接,以防给定文章甚至没有列出任何标签:

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';