简体   繁体   中英

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.

eg: Want Parts related to 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 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:

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 . And, the outer select needs to be fixed for the aggregation

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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