为了便于查询,您可以创建一个视图来避免不断加入。
create table object (
id serial unique,
object text primary key
);
create table tag (
id serial unique,
tag text primary key
);
create table object_tag (
object_id integer references object(id),
tag_id integer references tag(id)
);
insert into tag (tag) values ('English'), ('French'), ('German');
insert into object (object) values ('o1'), ('o2');
insert into object_tag (object_id, tag_id) values (1, 1), (1, 2), (2, 3);
create view v_object_tag as
select o.id object_id, o.object, t.id tag_id, t.tag
from
object o
inner join
object_tag ot on o.id = ot.object_id
inner join
tag t on t.id = ot.tag_id
;
现在查询好像它是一个表:
select *
from v_object_tag
where tag in ('English', 'German')
;
object_id | object | tag_id | tag
-----------+--------+--------+---------
1 | o1 | 1 | English
2 | o2 | 3 | German