Вопрос

I have a table with several attributes like this:

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

I want to know: what are the top attributes for the entries that have 'blue'? what are the top attributes for the entries that have 'blue' and 'red'?

For the second query the results should be:

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

I can build the query dynamically. I have this working, using this approach:

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

The problem is that if the inner query has a lot of entries the while process takes too long. Can anyone suggest a way to improve this?

Это было полезно?

Решение

Miguel. Try this:

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;

Of course you will need some indexes. These could be enough:

1 > id2, attribute
2 > attribute, id2

Другие советы

Here is an example for "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;

For "blue" and "red", you could just add another exists clause.

For performance, create an index on mytable(id2, attribute).

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top