gpt4 book ai didi

MySQL查询多对多关系表

转载 作者:行者123 更新时间:2023-11-29 15:43:51 25 4
gpt4 key购买 nike

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

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

结构如下:

帖子

  • ID
  • 标题
  • 描述

标签

  • ID
  • 姓名
  • 搜索引擎优化

item_tags

  • ID
  • post_id
  • tag_id

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

我的查询是:

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)

关于MySQL查询多对多关系表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57294114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com