JOIN two tables while grouping by an index and maching for multiple foreign ids

孤街醉人 提交于 2020-01-07 02:36:14

问题


I have the 3 Following Tables:

objects:

ObjectID ObjectDescription
1        "first"
2        "second"

attributes:

AttributeID AttributeDescription
1           "att1"
2           "att2"
3           "att3"
4           "att4"

attributelink:

AttributeID ObjectID
1           1
2           1
4           1

Now my question: I want now have some attributes selected and want to know, which Object has all my selected Attributes. I've tried the following:

SELECT * FROM `objects` 
    INNER JOIN `attributelink` 
         ON `objects`.`ObjectID` = `attributelink`.`ObjectID`
    WHERE `attributelink`.`AttributeID` =1 AND `attributelink`.`AttributeID` =2  
GROUP BY `objects`.`ObjectID` 

That obviously doesn't work, because one row can't have 2 AttributeIDs, but how can I archieve this?


回答1:


You have to join on the attributelink table once for each selected attribute you want to check for:

SELECT o.ObjectID
FROM objects o
INNER JOIN attributelink a1 ON o.ObjectID = a1.ObjectID AND a1.AttributeID = 1
INNER JOIN attributelink a2 ON o.ObjectID = a2.ObjectID AND a2.AttributeID = 2
GROUP BY o.ObjectID

Your test data doesn't show a whole lot about whether it works or not, but FWIW, here's the sqlfiddle.


Another way to do it is to use COUNT DISTINCT with HAVING and GROUP BY (sqlfiddle):

SELECT o.ObjectID
FROM objects o
INNER JOIN attributelink a ON o.ObjectID = a.ObjectID
WHERE a.AttributeID IN (1,2) --here you filter the rows on the attributes to test
GROUP BY o.ObjectID
HAVING COUNT(DISTINCT(a.AttributeID)) = 2 --# of attributes, means "having ALL"


来源:https://stackoverflow.com/questions/11674636/join-two-tables-while-grouping-by-an-index-and-maching-for-multiple-foreign-ids

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