从子集查询

时间:2014-04-24 21:05:00

标签: mysql sql nested

我有一个包含几个属性的表:

id  id2  attribute
--------------------------------
 1  100  blue 
 2  100  red
 3  100  green
 4  100  white
 5  102  blue
 6  102  green
 7  102  red
 8  103  red
 9  103  blue
10  103  white
11  104  red
12  104  black
13  104  green
14  104  orange
15  105  red
16  105  blue
17  105  green

我想知道: 具有“蓝色”的条目的顶级属性是什么? 具有“蓝色”和“红色”的条目的顶级属性是什么?

对于第二个查询,结果应为:

attribute   count1
--------------------
green       3
white       2

我可以动态构建查询。我有这个工作,使用这种方法:

SELECT
  mytable.attribute,
  count(mytable.id) as count1
FROM
    mytable,
    (SELECT
     id
    FROM
     mytable
    WHERE
     attribute in ('blue', 'red')
    GROUP BY
     id2
    HAVING
     count(distinct attribute) = 2) as t
WHERE
 mytable.id = t.id
and
 attribute NOT IN ('blue', 'red')
GROUP BY
 mytable.attribute
ORDER BY
 count1 desc

问题是如果内部查询有很多条目,则while过程需要太长时间。任何人都可以建议一种改进方法吗?

2 个答案:

答案 0 :(得分:1)

以下是" blue":

的示例
select t.attribute, count(*)
from mytable t
where exists (select 1
              from mytable tblue
              where tblue.attribute = 'blue' and
                    tblue.id2 = t.id2
             ) and
      t.attribute <> 'blue'
group by t.attribute
order by count(*) desc;

&#34; blue&#34;和&#34; red&#34;,你可以添加另一个exists条款。

为了提高效果,请在mytable(id2, attribute)上创建索引。

答案 1 :(得分:1)

米格尔。试试这个:

select attribute, count(1) as count1
from mytable
where id2 in (
    select distinct t.id2
    from mytable t
    join mytable t1 on (t1.id2 = t.id2 and t1.attribute = 'red')
    where t.attribute = 'blue')
and attribute not in ('blue', 'red')
group by attribute
order by count1 desc;

当然你需要一些索引。这些就足够了:

1 > id2, attribute
2 > attribute, id2