首页 > 解决方案 > 按两个标记系统过滤

问题描述

我有一个post关系tag_system_onetag_system_two

posttag_system_onethrough之间存在多对多的关系tag_system_one_post

posttag_system_twothrough之间存在多对多的关系tag_system_two_post

我想要一个用于多标签搜索的 SQL 查询。

当只有一个标签系统时,查询非常简单:

SELECT post.*
FROM post
JOIN tag_system_one_post ON post.id = tag_system_one_post.fk_post
JOIN tag_system_one ON tag_system_one_post.fk_tag_system_one = tag_system_one.id
WHERE tag_system_one.id IN (500, 533)
GROUP BY post.id
HAVING COUNT(*) = 2;

在此示例中,它检索具有两个标签500533(intersect) 的所有帖子。

Posts that only have tag `500` but not `533` will not be shown.

我能够执行上述声明,因为我使用的是COUNT(*) = 2. tag_system_two但是当我引入另一个标记系统( )时,这将不起作用。

有没有办法在没有子查询的情况下做到这一点?

标签: databasepostgresqldatabase-designrelational-database

解决方案


想了一会儿,我认为解决方案是:

HAVING COUNT(*) = 
no. of items selected in tagging_system_one 
MULTIPLIED BY
no. of items selected in tagging_system_two

推荐阅读