Nested SQL Query
-
27-09-2019 - |
Question
I have the following tables:
Club: Club_ID | Title | Created_Date | ...
Club_Intesect: User_ID | Club_ID | Access
I'm trying to select a variable number of clubs, and join the ID of the user with the highest access in that club. This person is considered the owner.
So if Club 100 has Members A, B, C with access 3,4, and 5 respectively: I want the final query to select from club:
Club.Club_ID Club.Title Club.Created_Date Club_Intersect.User_ID
100 | "Test Club" | "Creation Date" | C |
101 | "Test Club 2" | "Creation_Date" | Highest Access User |
...
Solution
SELECT * FROM Club c
JOIN Club_Intesect ci ON ci.Club_ID = c.Club_ID
WHERE ci.Access = (SELECT MAX(Access) FROM Club_Intesect WHERE Club_ID = c.Club_ID)
Not tested but you get the idea
OTHER TIPS
SELECT * FROM Club WHERE CLUB_ID = (SELECT Club_ID FROM Club_Intersect ORDER BY Access DESC LIMIT 1);
I think that would work for selecting the club you want, using a nested SQL Query. You didn't specify what you wanted in your returned results, because this query would only retrieve the Club columns.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow