I have a very simple table that has just part_id and part_type:
CREATE TABLE `temp` (
`part_id` INT NOT NULL ,
`part_type` CHAR( 5 ) NOT NULL
This has a long list of part id's and types. However, some parts have more than one type. How would I get the IDs of just the parts that have more than one type? I was thinking something like this would work:
SELECT * FROM temp WHERE part_in IN (SELECT count(part_id) as duplicates FROM temp WHERE 1 GROUP BY part_id) AND duplicates > 1
however, this is clearly just psuedocode and fails. Thanks for your help.
To select duplicate values, you need to create groups of rows with the same values and then select the groups with counts greater than one. You can achieve that by using GROUP BY and a HAVING clause.
Note − Use the INSERT IGNORE command rather than the INSERT command. If a record doesn't duplicate an existing record, then MySQL inserts it as usual. If the record is a duplicate, then the IGNORE keyword tells MySQL to discard it silently without generating an error.
select part_id from temp
group by part_id
having count(*) > 1
This will give you the part_id's with more than one row. You can then wrap that like your example query to get all of the part_id/part_type data for all parts with more than one row.
select * from temp
where part_id in (select part_id from temp
group by part_id
having count(*) > 1)
order by part_id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With