【发布时间】:2011-08-14 07:59:47
【问题描述】:
我是 SQL 和数据库的新手。我需要创建一个 SQL 查询来查找
all posts that have tags with tagname='t1'
帖子和标签之间的关系是多对多的
所以,我创建了架构和一些插入语句,如下所示:
create table Posts(
p_id int ,
p_name varchar
);
create table Tags(
t_id int ,
t_name varchar
);
由于多对多关系需要一个连接表,所以我也创建了它
create table Posts_Tags(
p_id int,
t_id int
);
insert into Posts values('1','P1' );
insert into Posts values('2','P2' );
insert into Posts values('3','P3' );
insert into Tags values ('1','t1');
insert into Tags values ('2','t2');
insert into Tags values ('3','t3');
insert into Tags values ('4','t4');
insert into Tags values ('5','t5');
insert into Posts_Tags values('1','1' );
insert into Posts_Tags values('1','2' );
insert into Posts_Tags values('2','1' );
insert into Posts_Tags values('2','3' );
insert into Posts_Tags values('3','5' );
现在,我应该如何进行 SQL 查询以获取所有带有t_name='t1' 标签的帖子?是否可以查询only the two tables Posts and Tags 并得到正确的结果?还是我也应该使用 Posts_Tags 表?
请原谅我对 rdbms 和 SQL 知之甚少。
【问题讨论】:
标签: sql create-table