Suppose, we’ve a table named college.
In this database we’ve the following columns: College ID, College name, State and Established in.
Now I want to find the names only of those colleges where the college have another branch in the same state.
Recently I’ve started learning database and couldn’t find the solution of this problem anywhere.
Please help me write the query in MySQL with explanation
I tried joining the same tables with alias as c1 and c2 and ran some query having select clause inside another select clause but it didn’t happen to work
3
Answers
I assume you forget to avoid self-matching in join. Also, use distinct college names as per requirement.
Try something like this.
You should have shown your query. A self join as you’ve mentioned should work.
You want the same college name and the same state. Hence:
By using
c2.id > c1.id
we make sure to get each pair just once. So with three rows for ‘Super College’ in ‘New York’ with IDs 1, 2, 3, you’d get 1/2, 1/3, 2/3.An alternative is aggreation. Group your rows such as to get one result row per college name and state and then list the IDs:
This would get you this row: Super College | New York | 1,2,3
If you’re using mysql version >= 8, you can use a window function.