繁体   English   中英

MySQL查询多对多关系表

[英]MySQL query for a many-to-many relationship table

我在这里遇到一些问题,我需要帮助。

我有一个名为posts的表,另一个名为tag的表,它们之间的多对多关系称为item_tags

这是结构:

帖子

  • ID
  • 标题
  • 描述

标签

  • ID
  • 名称
  • eo

item_tags

  • ID
  • post_id
  • tag_id

因此,假设现在我想通过已经具有tag_id来构建查询以匹配多个标签。 例如,让我们尝试匹配所有具有tag_id 11,tag_id 133和tag_id 182的帖子。我能做的是使用OR运算符选择它们,但这些并不是我想要的结果,因为我想要匹配所有具有全部的所有帖子提到的标签不仅包含一些标签

我的查询是:

SELECT * FROM item_tags tag_id = '11'或tag_id ='133'或tag_id ='182'

哪有错

这是表格的屏幕截图: https : //i.imgur.com/X60HIM5.png

PS:我想基于多个关键字(标签)进行搜索。

谢谢!

如果您希望所有已被所有三个标签标记的帖子,则可以使用:

select p.*
from posts p
where exists (select 1 from item_tags a where a.post_id = p.id and a.tag_id = 11)
  and exists (select 1 from item_tags a where a.post_id = p.id and a.tag_id = 133)
  and exists (select 1 from item_tags a where a.post_id = p.id and a.tag_id = 182)

如果您想要用这三个标签中的任何一个标签的帖子,请使用:

select p.*
from posts p
where exists (select 1 from item_tags a where a.post_id = p.id and a.tag_id = 11)
   or exists (select 1 from item_tags a where a.post_id = p.id and a.tag_id = 133)
   or exists (select 1 from item_tags a where a.post_id = p.id and a.tag_id = 182)

重要说明:我尚未测试!

SELECT * FROM posts WHERE id IN(SELECT post_id FROM item_tags WHERE item_tags.tag_id='11' OR item_tags.tag_id='133' OR item_tags.tag_id='182');

您可以按post_id对结果进行分组,然后仅保存所有链接了标签的标签

select * 
from posts 
where id in (
    select post_id 
    from item_tags 
    where tag_id in (11,133,182) 
    group by post_id 
    having count(tag_id)=3
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM