Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

filter duplicates in SQL join

When using a SQL join, is it possible to keep only rows that have a single row for the left table?

For example:

select * from A, B where A.id = B.a_id;

a1 b1
a2 b1
a2 b2

In this case, I want to remove all except the first row, where a single row from A matched exactly 1 row from B.

I'm using MySQL.

like image 272
Will Avatar asked Dec 02 '25 09:12

Will


1 Answers

This should work in MySQL:

select * from A, B where A.id = B.a_id GROUP BY A.id HAVING COUNT(*) = 1;

For those of you not using MySQL, you will need to use aggregate functions (like min() or max()) on all the columns (except A.id) so your database engine doesn't complain.

like image 133
Jack Edmonds Avatar answered Dec 04 '25 23:12

Jack Edmonds



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!