I have a table in a MySQL database that contains IDs of persons ´pid´ and names of cities city
that those people lived in. Since every person could have lived in more than one city during his/her live, one person can have more than one entry in that table.
PID | CITY
1 | Berlin
1 | New York
2 | Berlin
2 | Oslo
2 | New York
2 | Mexiko City
3 | Oslo
4 | Berlin
4 | Oslo
4 | Bagdad
4 | New York
4 | Mexiko City
There are two/three things I'd like to find out:
- What are the
pid
of all those persons, that lived in "Berlin" and in "New York" (the result should be [1, 2, 4]) - What are the other cities that people lived in, that once lived in "Berlin" and in "New York" (the result should be ["Oslo", "Mexiko City", "Bagdad"])
- It would be even better to get the counts, how often those cities occur in the table. (the result should be ["Oslo" -> 2 , "Mexiko City" -> 2, "Bagdad" -> 1])
How do I have to design my queries, to find out these things (and not overstress my database Server)?