简体   繁体   中英

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.

Though this a brute force solution, it will work using EXISTS . Waiting for a better solution.

SELECT a.dataID 
FROM DataID a WHERE a.dataID = 1 
    AND EXISTS (SELECT 1 FROM Attributes d WHERE d.DataID = 1 AND d.attributeID = 1)
    AND EXISTS (SELECT 1 FROM Attributes d WHERE d.DataID = 1 AND d.attributeID = 2)
    AND EXISTS (SELECT 1 FROM Attributes d WHERE d.DataID = 1 AND d.attributeID = 3)

A GROUP BY solution is possible.

SELECT dataID 
FROM Attributes 
WHERE dataID = 1 AND (attributeID = 1 OR attributeID = 2 OR attributeID = 3)
GROUP BY dataID
HAVING COUNT(*) = 3

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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