I heard people say that table joins can be used everywhere to replace subqueries. I tested it in my query, but found that the corresponding dataset was only received when I used subqueries. I could not get the same dataset using joins. I’m not sure that what I found is correct, because I am new to RDBMS, so I have not survived so much. I will try to draw a diagram (in words) of the database in which I experimented:
There are two tables in the database:
Users( ID , name, city) and friendship ( ID , Friend_ID )
Goal: The user table is for storing simple user data, and the friendship table is friendship between users. The friendship table has both columns as foreign keys that reference User.ID. Tables have a many-to-many relationship between them.
Question: I need to get Users.ID and Users.Name of all users who are not familiar with a specific user x, but from the same city (the same as the fb friend suggestion system).
Using a subquery, I can achieve this. The request looks like this:
SELECT ID, NAME
FROM USERS AS U
WHERE U.ID NOT IN (SELECT FRIENDS_ID
FROM FRIENDSHIP,
USERS
WHERE USERS.ID = FRIENDSHIP.ID AND USERS.ID = x)
AND U.ID != x AND CITY LIKE '% A_CITY%';
Example entries:
Users
Id = 1 Name = Jon City = Mumbai
Id = 2 Name = Doe City = Mumbai
Id = 3 Name = Arun City = Mumbai
Id = 4 Name = Prakash City = Delhi
Friendship
Id = 1 Friends_Id = 2
Id = 2 Friends_Id = 1
Id = 2 Friends_Id = 3
Id = 3 Friends_Id = 2
, . ? , , . .
. , : , . "" U , ( "", , , , x. , ).