SQL - 匹配一组记录

时间:2016-09-26 16:48:27

标签: sql sql-server sql-server-2008-r2

让我们说我有很多关系:

Profile  <-  Profile_Attribute  -> Attribute
-------      -----------------     ---------
ProfileID    Profile_AttributeID   AttributeID
Name         ProfileID             Name
             AttributeID
             Value

查看数据时,配置文件有2个属性,属性A和属性B.我想查找具有匹配值的所有属性的任何配置文件记录,而无需对属性ID&名称进行硬编码。所以基本上我想将一个表传递给包含属性的查询,它会找到匹配的任何配置文件记录。只有确切的属性相同时,配置文件记录才会匹配,即。它不具有更多属性,对具有不同值的属性具有更少的属性。

这是我提出的SQL。只是想知道是否有更好的方法来做到这一点。

--Declare the set of attributes/values that I want to find matching profiles for
DECLARE @tblCheck TABLE
(
    AttributeID INT,
    Value VARCHAR(255)
)

--We're looking for any profile record that has an attribute 2 of abc and 
--an attribute 1 of xyz, but nothing else
INSERT INTO @tblCheck (AttributeID, Value) VALUES (2, 'abc')
INSERT INTO @tblCheck (AttributeID, Value) VALUES (1, 'xyz')

--Find all profiles that have the same attributes and the same values
SELECT 
    p.ProfileID, 
    COUNT(*)
FROM
    [Profile] p
JOIN
    [Profile_attribute] pa ON pa.ProfileID = p.ProfileID
LEFT JOIN
    @tblCheck c ON pa.AttributeID = c.AttributeID AND
                   --Match on exact value or a wildcard
                   (pa.Value = c.Value OR pa.Value = '*')
GROUP BY
    p.ProfileID
HAVING
    COUNT(*) = (SELECT COUNT(*) FROM @tblCheck)

1 个答案:

答案 0 :(得分:1)

我认为你只是想找到这样的东西:

select c.ProfileId, Count(*) from @tblCheck as a
inner join Profile_attribute as b on a.AttributeID = b.AttributeID and a.Value = b.Value
inner join Profile as c on c.ProfileID = b.ProfileID
Group by c.ProfileID