一个项目 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/