【问题标题】:Select from ManyToMany only if all Ids apply仅当所有 Id 都适用时才从 ManyToMany 中选择
【发布时间】:2013-06-29 06:33:39
【问题描述】:

您好,我正试图将其编入一项原则 2 声明中,不幸的是我现在脑子里有结。

我有 3 张桌子

post

id | unrelated stuff

post_has_tag

post_id | tag_id
1         1
1         2
2         2

tag

 id | name
 1    smth
 2    smthelse

现在我想使用一些标签导航,有点像 stackoverflow 上的这里,这就是我的问题所在。如果所有 id 都适用,我只想从我的 m2n 表中选择 post_id。而且我在这里有点愚蠢,因为我所有的尝试要么给我两个条目,要么都不给我。

如果你能给我sql我会很好,如果你能给我dql那就太棒了

E:澄清 所以总结一下:

我使用像 $object->filterPostsByTag(array(1,2)); 这样的东西现在我只想要至少分配了 id 1 和 2 的标签的帖子。我尝试加入的结果要么返回两个帖子,要么都不返回。

【问题讨论】:

    标签: mysql sql doctrine-orm dql


    【解决方案1】:

    如果您希望应用所有 id(可能是“标记”id),则使用带有 having 子句的聚合:

    select pht.post_id
    from post_has_tag pht
    group by pht.post_id
    having count(distinct pht.tag_id) = (select count(distinct t.tag_id) from tag t)
    

    编辑:(OP修改后)

    如果你只想要两个特定的标签,你可以使用相同的想法:

    如果您希望应用所有 id(可能是“标记”id),则使用带有 having 子句的聚合:

    select pht.post_id
    from post_has_tag pht
    group by pht.post_id
    having max(pht.tag_id = 1) > 0 and
           max(pht.tag_id = 2) > 0
    

    这将返回具有两个标签的所有帖子。如果你想要两个标签 没有别的:

    select pht.post_id
    from post_has_tag pht
    group by pht.post_id
    having max(pht.tag_id = 1) > 0 and
           max((pht.tag_id <> 1) or (pht.tag_id <> 2)) = 0
    

    【讨论】:

    • 是的 sql 可以工作,现在是时候教教条2了,他们的解析器似乎有点不对劲
    猜你喜欢
    • 2019-07-22
    • 1970-01-01
    • 2019-11-17
    • 1970-01-01
    • 1970-01-01
    • 2015-10-10
    • 1970-01-01
    • 2021-04-02
    • 2020-10-18
    相关资源
    最近更新 更多