Return all rows where the entire list of a relation matches (as opposed to any combination of)

谁说胖子不能爱 提交于 2019-12-11 20:16:30

问题


With the following simple table structure:

Data
----------
id

Tag
----------
id

TaggedData
----------
id
tag_id
data_id

If I had a list of Tag ids, how would I fetch every row of Data where every row of Tag in my list has a relation to a row of Data matched and not a subset thereof?

Here's the query I have right now that doesn't work:

    SELECT
        Data.*

    FROM
        Data
    LEFT JOIN
        TaggedData ON (Data.id = TaggedData.data_id)
    LEFT JOIN
        Tag ON (Tag.id = TaggedData.tag_id)

    WHERE
        Tag.id IN ('1' , '2')

Specifically: This one isn't working because it will return any row of Data that is related to Tag 1 or 2. Not 1 and 2.


回答1:


This is called "relational division"

   SELECT 
        Data.ID  
    FROM 
        Data 
    INNER JOIN 
        TaggedData ON (Data.id = TaggedData.data_id) 
    INNER JOIN 
        Tag ON (Tag.id = TaggedData.tag_id) 
    WHERE 
        Tag.id IN ('1' , '2') 
    HAVING COUNT(DISTINCT tag.iD)=2


来源:https://stackoverflow.com/questions/12711699/return-all-rows-where-the-entire-list-of-a-relation-matches-as-opposed-to-any-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!