当我有两个单独的表时,我想知道如何设计我的SQL查询,但是应该一起工作......
likes
表
列 - idlikes,idusers,like_what
user_follow
表
列 - idfollow,关注者,关注
为优化/性能设计查询的最佳方法是什么?可以组合查询吗?或者我应该像这样分开每个查询:
$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..
}
更新
$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;
}
答案 0 :(得分:1)
这将在一个查询中执行
SELECT L.*
FROM likes L
JOIN user_follow F ON L.idusers = F.following
WHERE F.follower = ?
关于命名的注释:在sql中,每行包含一个值,因此列名通常是单数。因此likes.idusers
通常为likes.iduser
我还要明确说明它是否是iduser上的FK,所以在user_follow表中我将follower
命名为iduser_follower
而将following
命名为isuser_following