0

我有以下 3 个表格:

对象:

ObjectID ObjectDescription
1        "first"
2        "second"

属性:

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

属性链接:

AttributeID ObjectID
1           1
2           1
4           1

现在我的问题:我现在想选择一些属性并想知道哪个对象具有我所有选择的属性。我尝试了以下方法:

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

这显然行不通,因为一行不能有 2 个 AttributeID,但我该如何归档呢?

4

1 回答 1

1

attributelink对于要检查的每个选定属性,您必须在表上加入一次:

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

您的测试数据并没有显示很多关于它是否有效,但是 FWIW,这里是 sqlfiddle


另一种方法是使用COUNT DISTINCTand HAVING( GROUP BYsqlfiddle )

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"
于 2012-07-26T17:23:39.757 回答