mysql - 从子集查询

标签 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 过程花费的时间太长。谁能提出一种改进方法?

最佳答案

米格尔.试试这个:

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

关于mysql - 从子集查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23279787/

相关文章:

mysql - 按整数排序不适用于我的连接查询

php - 如何将数据从 PHP 插入到 MySQL DB

python - Python中字典结构中的嵌套字典,希望以特定方式输出

python - 如何在 Python 中创建嵌套字典?

mysql - 在 Ubuntu 上运行 Rails 时遇到问题

mysql - Hive - 成功导入 Sqoop 后没有表列出

mysql - 基于带有子选择的 where 语句更新 mysql 中的列

sql - 如果在稍后在事务中不使用的 CTE 内执行,为什么 SELECT...FOR UPDATE 不起作用?

MySQL 左连接多行

java - Firebase -(具有多个子节点的 DataSnapshot)- NullPointerException