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

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

sql - MySQL query finding matches across multiple rows

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

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

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...