gpt4 book ai didi

mysql - 从子集查询

转载 作者:行者123 更新时间:2023-11-29 08:03:08 25 4
gpt4 key购买 nike

我有一个包含多个属性的表,如下所示:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com