假设我有一个表,其中列出的项目和属性如下:

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

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

有帮助吗?

解决方案

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

其他提示

的最有效的方式来做到这一点是具有自连接:

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

,一些人使用另一种解决方案是与A组特技BY:

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

但作为一个JOIN,这取决于使用哪个品牌RDBMS的GROUP BY溶液可能并不那样有效。还一种方法可以缩放更好,因为在表格中的体积增大。

SELECT * FROM表,其中的事= '蛙'

没有什么比清楚地知道你想要什么。

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

您也可以分别查询每个属性,然后相交他们...

/*
-- 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'

创建两个表,项目中的一个和属性之一。结果 项目可以命名,intAttributeID,其中intAttributeID是属性表的外键引用。这样,你可以做一个select语句根据关你关心什么的。

但也许这可以帮助你:

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

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

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

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

如果可能的话,我会重新设计。这是不是你将永远能够什么有效的查询在12个值在同一时间(这将需要12连接)

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

没见过一个数据库但所使用此模型上并没有遇到严重的性能问题最终。这种设计看起来优雅到非数据库的人,但实际上通常是设计不好的数据库的一个标志。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top