I have sql table:
id user city
1 Alisa New York
2 Alisa Sydney
3 Alisa Rom
4 Alisa Toronto
5 Bob Rom
6 Bob Moskow
7 Bob Sydney
8 Tom Sydney
And I need get how many same cities have other users for Bob for example.
SELECT user, count(DISTINCT city) FROM table WHERE city IN (
SELECT city FROM table WHERE user = 'Bob'
) AND user != 'Bob' GROUP BY user
and result is:
user count(DISTINCT city)
Alisa 2
Tom 1
Do you know other best way to make this request? Is it ok for huge table?
You could create a temporary table, in which you will store the cities, in which Bob was and then do an inner join between your table and the temporary table you created.