简体   繁体   English

选择所有具有相同ID的行

[英]Select all rows that have same ID

I have this table: 我有这张桌子:

ID | Part
1  | A
1  | B
1  | C
2  | B
2  | C
3  | A
3  | D
3  | E
4  | B
4  | D

and want a query that will grab all ID's that have an A, and return a list of all other parts with that ID. 并希望查询将获取所有具有A的ID,并返回具有该ID的所有其他部分的列表。

eg: Want Parts related to B: 例如:想要与B相关的零件:

Part | Count
 A   | 1
 C   | 2
 D   | 1

What I have currently: 我目前所拥有的:

SELECT * FROM tble WHERE ID IN (SELECT DISTINCT ID FROM tble t WHERE Part = ?)
GROUP BY Part ORDER BY COUNT(Part) DESC

This works, but is quite slow and I'm looking to improve it, but having difficulty 该方法有效,但是速度很慢,我正在寻求改进,但是有困难

Simplify this.. Once you have the logic down, then add back in the SELECT * FROM.. 简化此过程。一旦您掌握了逻辑,然后在SELECT * FROM中重新添加。

SELECT Part, COUNT(Part) As Count_of_Part
GROUP BY Part ORDER BY COUNT(Part) DESC

Do a join from the table back to itself on ID, and then count the distinct values that pop up: 将表从连接返回到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

Your query is not unreasonable, although the distinct is unnecessary and I would use exists rather than in . 您的查询不是没有道理的,尽管distinct是不必要的,我将使用exists而不是in And, the outer select needs to be fixed for the aggregation 而且,外部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;

Then, to optimize this query, you want an index: 然后,要优化此查询,您需要一个索引:

create index idx_tble_id_part on tble(id, part);

This can be simply done by joining back to the table: 可以简单地通过加入表来完成:

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

SQL Fiddle Demo SQL小提琴演示

You should be able to do this by grouping the data. 您应该能够通过对数据进行分组来做到这一点。

Try something like this: 尝试这样的事情:

SELECT part, COUNT(id) AS TotalCountId
FROM TABLE_NAME
GROUP BY ID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM