Sql 如何从Postgres表中获取数据(多对多)
我需要链接文章表和标签。我创建了3个表Sql 如何从Postgres表中获取数据(多对多),sql,postgresql,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 Articl
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请求以接收文章及其所有标记?加入三个表:
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;
连接三个表:
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;
作为@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';
作为@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';
一个简单的连接查询。请发布您的代码、数据集和期望的结果集。请删除两个标记中的一个,postgres或mysqlI,我想这是PostreSQL。删除MySQL标记。一个简单的连接查询。请发布您的代码、数据集和期望的结果集。请删除两个标记中的一个,postgres或mysqlI,我想这是PostreSQL。删除MySQL标签。谢谢,works,以及如何使标签由数组输出?谢谢,works,以及如何使标签由数组输出?