I have two tables Schools and Users
Table School
-----------------------------------------------------
| id | name | city | major | userID |
----------------------------------------------------|
| 1 | school A | chicago | CS | 1 |
----------------------------------------------------|
| 2 | school B | chicago | CS | 1 |
----------------------------------------------------|
| 3 | school A | chicago | CS | 2 |
----------------------------------------------------|
| 4 | school C | chicago | Art | 2 |
----------------------------------------------------|
| 5 | school B | chicago | CS | 3 |
----------------------------------------------------|
| 6 | school D | chicago | Math | 3 |
----------------------------------------------------|
| 7 | school A |New York | CS | 3 |
----------------------------------------------------|
| 8 | school B | chicago | Art | 3 |
-----------------------------------------------------
Table Users
--------------------
| id | name |
____________________
| 1 | User A |
____________________
| 2 | User B |
____________________
| 3 | User C |
____________________
| 4 | User D |
____________________
| 5 | User E |
____________________
The userID field in the schools table is a foreign key to the id field in the users table. I want to write a MySQL statement that takes a given userID and lists all classmates of that user.
So, for the example above, a class mate of User A (ID#1) is a user that went to the same school as User A, is located in the same city, and has the same major. Thus, valid classmates for User A are only User B (ID#2) AND User C (ID#3).
Right now, I am using two MySQL statements to accomplish this goal. The first one is this
SELECT id FROM schools WHERE userID = '1'
which lists all schools for User A. Then I use PHP to loop through the results and for each row I run the following
SELECT userID from schools WHERE
name city LIKE '%$chicago%'
AND name LIKE '%$school A%'
AND major LIKE '%$CS%'
This works fine and returns the right list of userIDs. However, I am wondering if there is a more efficient way to do this in one SQL statement and without having to use PHP.
You can do it like this:
In the
auxquery you select thename‘s andcity‘s of a@userand then select alluserswith those requirements and that aren’t the@useritself.You may replace ‘User A’ by a variable.