I’m wondering how to design my SQL query when I have two separate tables, but should work together…
likes table
Columns – idlikes, idusers, like_what
user_follow table
Columns – idfollow, follower, following
What is the best way to design a query for optimization/performance? Can queries be combined? Or am I supposed to separate each query like this:
$iduser = 1 //I am user 1 in database.
$get = $db -> prepare("SELECT * FROM user_follow WHERE follower = ?")
$get -> execute(array($iduser));
while($row = $get->fetch(PDO::FETCH_ASSOC)){
$following = $row['following']; // get id of user that i'm following
$likes = $dbh->prepare("SELECT * FROM likes WHERE idusers = ?");
$likes->execute(array($following));
// do what I need to..
}
UPDATE
$following = $dbh->prepare("SELECT L.* FROM likes L JOIN user_follow F on L.iduser = F.iduser_following WHERE F.iduser_follower = ?");
$following->execute(array($iduser));
while($row_following = $following->fetch(PDO::FETCH_ASSOC))
{
$id1 = $row_following['L.iduser'];
echo $id1;
}
This will do it in one query
A note on naming: In sql each row contains one value thus column names are typically singular. Thus
likes.iduserswould typically belikes.iduserI would also make it clear if it is a FK on iduser, so in the user_follow table I would name
followerasiduser_followerandfollowingasisuser_following