我有这张桌子:
ID | Part
1 | A
1 | B
1 | C
2 | B
2 | C
3 | A
3 | D
3 | E
4 | B
4 | D
并希望查询能够获取所有拥有A的ID,并返回包含该ID的所有其他部分的列表。
例如:想要与B相关的零件:
Part | Count
A | 1
C | 2
D | 1
我目前的情况:
SELECT * FROM tble WHERE ID IN (SELECT DISTINCT ID FROM tble t WHERE Part = ?)
GROUP BY Part ORDER BY COUNT(Part) DESC
这有效,但速度很慢,我希望改进它,但有困难
答案 0 :(得分:0)
简化此..一旦你关闭逻辑,然后在SELECT * FROM ..
中加回SELECT Part, COUNT(Part) As Count_of_Part
GROUP BY Part ORDER BY COUNT(Part) DESC
答案 1 :(得分:0)
从ID返回到自身的连接,然后计算弹出的不同值:
SELECT b.part, COUNT(DISTINCT b.id)
FROM
table as a
INNER JOIN table as b ON
a.id = b.id AND
a.part <> b.part
WHERE
a.part = 'B'
GROUP BY b.part
答案 2 :(得分:0)
您的查询并非不合理,但distinct
是不必要的,我会使用exists
而不是in
。并且,需要为聚合
select
SELECT t.part, COUNT(*)
FROM tble t
WHERE EXISTS (SELECT 1 FROM tble t2 WHERE t2.ID = t.ID AND t2.Part = ?)
GROUP BY t.Part
ORDER BY COUNT(*) DESC;
然后,要优化此查询,您需要一个索引:
create index idx_tble_id_part on tble(id, part);
答案 3 :(得分:0)
这可以通过加入表格来完成:
SELECT t1.part
,count(*)
FROM tble t1
INNER JOIN tble t ON t.id = t1.id
AND t.part = 'B'
AND t1.part <> t.part
GROUP BY t1.part
答案 4 :(得分:0)
您应该可以通过对数据进行分组来实现此目的。
尝试这样的事情:
SELECT part, COUNT(id) AS TotalCountId
FROM TABLE_NAME
GROUP BY ID