SQL查询设计有两个单独的表? MySQL PHP PDO性能

时间:2013-02-02 00:29:00

标签: mysql sql pdo database-performance

当我有两个单独的表时,我想知道如何设计我的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;
}

1 个答案:

答案 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