mysql - SQL : ids containing specific arrays in a specific way

标签 mysql sql ruby-on-rails ruby postgresql

一个项目 table: items 有许多分类法 table: taxonomies 使用连接表 item_taxonomies (item_id, taxonomy_id)

使用分类组搜索项目。

例子:

taxo_group_1 = [1, 2, 3]
taxo_group_2 = [4, 5]

SQL 应该以这种方式找到所有包含在两个数组中的 items:

如果我有这些元素:

item_1 id=1
   taxo_1 id=11
   taxo_2 id=12
   taxo_3 id=13

item_2 id=2
   taxo_3 id=13
   taxo_4 id=14

使用 [11, 12][13] 搜索将返回 item_1 而不是 item_2,因为item_1 具有分类法在 [11, 12] 和 [13] 中

item_2 不会被返回,因为它在 [11, 12]

中没有分类法

到目前为止:

"taxonomies"."id" IN (11, 12, 13) AND "taxonomies"."id" IN (13)

当然不行。

最佳答案

您可以使用此查询获得所需的输出:

select item from (
    select item, count(distinct taxonomy_id) as count from items  
    join taxonomies on items.item_id = taxonomies.item_id
    where taxonomies.taxonomy_id in (11,12,13)
    group by item
) as T where count = 3

关于mysql - SQL : ids containing specific arrays in a specific way,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49152638/

相关文章:

ruby-on-rails - 将 Flash 消息呈现为 JSON 响应的 Rails DRY 机制

ruby-on-rails - 在 Rails 4 路由中强制使用 https

ruby-on-rails - Rails教程区分大小写不起作用

mysql - 我们可以从一个表中删除与其他表使用一对多关系相关的记录吗?

bind_result 上的 php 空值

MySQL - 如何通过单个操作更改所有数据库上的列?

mysql - 运行 2 个 mysql 实例,一个本地 3306,一个用于 ampps?

c# - 如何在多个 Linq IQueryable 上执行 sql Union

mysql - 从映射表中选择类别

sql - 在 SQL 过程中使用 UTL_MAIL 时出错