I'm fairly new to SQL and am trying to get a grasp on the best practices. I have a question about using the JOIN
keyword. Right now, I have a <table>
on the front end that displays "practices" from a SQL table, but only if that "practice" has a "representative" that is owned by the current user(the "manager"). Right now what I am doing is grabbing the "representatives" that belong to the "manager" (the current logged in user) and looping through those to grab the id of the "representative" and push it into an array. When I write my query, I am grabbing all the practices that belong to any of the "representative" id's in that array and building my query that way:
// Grabbing the reps that are assigned to current user
$owned_reps_id = $database->run_query("SELECT id FROM reps WHERE owner={$_SESSION['current_user_id']}");
$owned_reps_array = array();
while($owned_rep = mysqli_fetch_assoc($owned_reps_id)){
// Throwing non-duplicate values in an array
if(!in_array($owned_rep['id'], $owned_reps_array)){
array_push($owned_reps_array, $owned_rep['id']);
}
}
// Building the query to only grab "practices" where it's `owner` column matches an id in the $owned_reps_array
$query = "SELECT * FROM practices WHERE";
if(!empty($owned_reps_array)){
foreach($owned_reps_array as $rep_owner){
$query .= " owner={$rep_owner}";
if (end($owned_reps_array) !== $rep_owner){
$query .= " OR";
}
};
};
$query .= " ORDER BY practice_name ASC";
$all_practices = $database->run_query($query);
What I am wondering here is if I took the long way around this. This code does work the way I want it to, but I feel like I went through a lot just to get the result. Again, what I am doing is:
1) Grab all representatives that have the current manager's id saved in the 'owner' column.
2) Of those representatives, then go look into the practices table and grab all the practices that have have any of the id's pulled from the representatives. (Again there is an 'owner' column in the "practices" SQL table that stores the ID of the "representative" it is owned by)
Is this something I can do using JOIN
or is the route I took efficient?