0

我想知道当我有两个单独的表时如何设计我的 SQL 查询,但应该一起工作......

likes桌子

- idlikes、idusers、like_what


user_follow桌子

- idfollow、follower、following


设计优化/性能查询的最佳方法是什么?可以合并查询吗?或者我应该像这样分开每个查询:

$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;
}
4

1 回答 1

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 表中,我将命名followeriduser_followerfollowingisuser_following

于 2013-02-02T00:39:12.690 回答