Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have two tables, Data(Name, dataID) and Attributes(Name, attributeID, dataID) with a one-to-many relationship. One dataID might be associated with many attributeID's.

What I want to do is run a query that finds all dataIDs that have a specific set of attributeIDs. I can't do:

SELECT dataID
FROM Attributes
WHERE dataID = 1 AND (attributeID = 1 OR attributeID = 2 OR attributeID = 3);

That would grab all dataID's with any one of those attributes, I want the dataID's that have all of those attributes.

Suggestions?

Still wrapping my head around queries using more than very basic selects.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
344 views
Welcome To Ask or Share your Answers For Others

1 Answer

As you need to read three different rows of the Attributes table, I suggest to use JOIN's to avoid subqueries.

SELECT a1.dataID
FROM
    Attributes a1
    JOIN Attributes a2 ON
        a1.dataID=a2.dataID
    JOIN Attributes a3 ON
        a2.dataID=a3.dataID
WHERE
    a1.dataID = 1 AND
    a1.attributeID = 1 AND
    a2.attributeID = 2 AND
    a3.attributeID = 3;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...