简体   繁体   English

MySQL查询,在多对多关系上相交

[英]MySQL query, intersection on many-to-many relationship

Does someone have a good idea/solution how to achieve this? 有人有一个好主意/解决方案如何实现这一目标吗?

Situation is: I have the tables 'releases' and 'ntags', related via 'releases_ntags' (containing 'release_id' and 'ntag_id') 情况是:我有通过“ releases_ntags”关联的表“ releases”和“ ntags”(包含“ release_id”和“ ntag_id”)

And I would like to fetch results for releases via the ntag's 'slug'. 我想通过ntag的“ slug”获取发布的结果。

I manage to have this semi-working: 我设法做到了这一点:

sql sql

SELECT r.id, r.name
FROM releases r
LEFT JOIN ntags_releases rt ON rt.release_id = r.id
JOIN ntags nt ON nt.id = rt.ntag_id
AND (nt.name = ('TAG_1') OR nt.name = ('TAG_2'))
GROUP BY r.id, r.name

So far so good, but this gives me all releases with "TAG_1" PLUS all releases with "TAG_2" (and off course those with both tags). 到目前为止好,但是这给了我与“TAG_1”所有版本加上 “TAG_2”(当然那些有两个标签关闭)的所有版本。

But what I need is to only get the intersection of the tags, say: 但是我需要的只是获取标签的交集,例如:

"releases with 'TAG_1' AND 'TAG_2'" “发布时带有'TAG_1' 'TAG_2'”

So i tried with: 所以我尝试了:

...
AND (nt.name = ('TAG_1') AND nt.name = ('TAG_2'))
... 

But this leads in an empty result. 但这导致空结果。 Does anyone have an idea how to achieve this? 有谁知道如何实现这一目标? Don't know how to go further on this and would really appreciate some input! 不知道该如何做得更进一步,非常感谢您的投入!

thx 谢谢

You can demand that two distinct ntags are present in the having clause: 您可以要求在having子句中存在两个不同的ntag:

SELECT  r.id, r.name
FROM    releases r
JOIN    ntags_releases rt
ON      rt.release_id = r.id
JOIN    ntags nt
ON      nt.id = rt.ntag_id
WHERE   nt.name in ('TAG_1', 'TAG_2')
GROUP BY
        r.id, r.name
HAVING
        COUNT(distinct nt.name) = 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM