问一下有关多对多关系查询的问题

2022-09-13 17:36:42 +08:00
 Rokaki
图片一张表,标签一张表
它们之间多对多关联起来,现在我想查询同时含有标签 a,b 的图片。
eg,图片 1 含有标签 a ;图片 2 含有标签 b ;图片 3 含有标签 a,b 。
怎么把图片 3 查询出来
1035 次点击
所在节点    程序员
5 条回复
seth19960929
2022-09-13 18:49:48 +08:00
select img_id from relations_table where tag_id='a' and tag_id='b' limit 1
j0hnj
2022-09-13 19:05:28 +08:00
create table images (id int, url varchar(100));
create table tags (id int, tag varchar(10));
create table image_tags (image_id int, tag_id int);

insert into images values (1, 'image_1'), (2, 'image_2'), (3, 'image_3');
insert into tags values (1, 'tag_a'), (2, 'tag_b');
insert into image_tags values (1,1),(2,2),(3,1),(3,2);

select T.id, T.url from (select images.id, images.url from images inner join image_tags on images.id = image_tags.image_id inner join tags on tags.id = image_tags.tag_id where tags.tag = 'tag_a') T inner join image_tags on T.id = image_tags.image_id inner join tags on tags.id = image_tags.tag_id where tags.tag = 'tag_b';
j0hnj
2022-09-13 19:28:44 +08:00
eason1874
2022-09-13 20:05:10 +08:00
经典场景,不会可以参考 WordPress 的关系表设计
FYFX
2022-09-13 20:14:27 +08:00
等价与含标签 a 的图片的表和含标签 b 的图片的表做 inner join

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/879777

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX