什么是用于选择项/属性列表中具有多个属性的项的SQL语句?

时间:2009-05-29 19:29:50

标签: sql relational-division sql-match-all

假设我有一个包含项目和属性的表,如

frog    green
cat     furry
frog    nice
cat     4 legs
frog    4 legs

从items列中我想选择同时具有绿色和4个腿属性的对象。在这种情况下,我希望能够回到青蛙对象。执行此操作的最有效查询是什么?

9 个答案:

答案 0 :(得分:9)

select  item.name 
from    item 
where   item.attribute in ('4 legs', 'green') 
group by item.name 
having  count(distinct item.attribute) = 2

答案 1 :(得分:2)

最有效的方法是使用自我加入:

SELECT * FROM attributes a1 
JOIN attributes a2 USING (item_name) -- e.g. frog
WHERE a1.value = 'green' AND a2.value = '4 legs';

有些人使用的另一个解决方案是使用GROUP BY的技巧:

SELECT item_name FROM attributes
WHERE value IN ('4 legs', 'green')
GROUP BY item_name
HAVING COUNT(*) = 2;

但GROUP BY解决方案可能效率不如JOIN,具体取决于您使用的RDBMS品牌。此外,随着表格中的音量增加,一种方法可能会更好地扩展。

答案 2 :(得分:1)

从表中选择*,其中thing ='frog'

什么都不知道你想要什么。

答案 3 :(得分:1)

select
    item, count(*)
from
    @temp
where
    attribute in ('4 legs','green')
group by
    item
having
    count(*) = 2 -- this "2" needs to be replaced with however many attributes you have

答案 4 :(得分:1)

您也可以单独查询每个属性,然后将它们相交......

/*
-- create sample table...
create table #temp1
    (item varchar(max),
    attrib varchar(max))

-- populate sample table (SQL 08)...
insert #temp1
values ('frog', 'green'), ('cat', 'furry'), ('frog', 'nice'), ('cat', '4 legs'), ('frog', '4 legs')
*/


SELECT  item
FROM    #temp1
WHERE   attrib = 'green'
INTERSECT
SELECT  item
FROM    #temp1
WHERE   attrib = '4 legs'

答案 5 :(得分:0)

很难,因为它不是标准化模型。这是一个周末。

您要跨多个未连接的行进行过滤,因此您必须依次提取每个属性,然后匹配项目。

SELECT
   item
FROM
    (SELECT
        item
    FROM
        Mytable
    WHERE
        attribute = '4 legs') k1
    JOIN
    (SELECT
        item
    FROM
        Mytable
    WHERE
        attribute = 'green') k2 ON k1.item = k2.item

答案 6 :(得分:0)

创建两个表,一个项目和一个属性 items可以是name,intAttributeID,其中intAttributeID是Attributes表的外键引用。这样你就可以根据你关心的事情做一个选择陈述。

答案 7 :(得分:0)

但也许这可以帮到你:

SELECT * 
FROM tbl t1
INNER JOIN tbl t2 ON t1.Name = t2.Name
WHERE t1.Attribute = 'green' AND t2.Attribute = '4 legs'

答案 8 :(得分:0)

如果可能的话,我会重新设计。这不是你将能够同时有效地查询12个值的东西(它将需要12个连接)

请阅读此维基百科文章 http://en.wikipedia.org/wiki/Entity-Attribute-Value_model#Downsides

从未见过使用此模型但最终未遇到严重性能问题的数据库。这种设计对于非数据库人来说看起来很优雅,但实际上通常是设计糟糕的数据库的标志。

相关问题