6

假设我有一个表,其中列出了项目和属性,例如,

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

从项目列中,我想选择具有绿色和 4 条腿属性的唯一对象。在这种情况下,我希望只取回青蛙对象。执行此操作的最有效查询是什么?

4

9 回答 9

9
select  item.name 
from    item 
where   item.attribute in ('4 legs', 'green') 
group by item.name 
having  count(distinct item.attribute) = 2
于 2009-05-29T19:37:24.107 回答
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 品牌。此外,随着表中容量的增加,一种方法可能会更好地扩展。

于 2009-05-29T19:37:33.077 回答
1

select * from table where thing='frog'

没有什么比知道你想要什么更好的了。

于 2009-05-29T19:33:01.637 回答
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
于 2009-05-29T19:38:26.553 回答
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'
于 2009-05-29T19:55:01.170 回答
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
于 2009-05-29T19:34:20.727 回答
0

创建两个表,一个项目和一个属性。
项目可以是名称、intAttributeID,其中 intAttributeID 是对 Attributes 表的外键引用。这样你就可以根据你关心的任何事情来做一个选择语句。

于 2009-05-29T19:34:29.060 回答
0

但也许这可以帮助你:

SELECT * 
FROM tbl t1
INNER JOIN tbl t2 ON t1.Name = t2.Name
WHERE t1.Attribute = 'green' AND t2.Attribute = '4 legs'
于 2009-05-29T19:44:25.873 回答
0

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

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

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

于 2009-05-29T21:51:10.373 回答