我无法获取某些数据......我想知道是否有人可以帮助我,
我有4张桌子(喜欢,关注,评论,用户)
我希望能够在用户喜欢/ comments / follow / etc ...(如果用户关注特定用户)时填充我的页面。
喜欢
idlikes idusers iditem
1 1 5
2 2 4
3 2 22
遵循
idfollow idusers_follower idusers idbusiness
1 1 2
2 1 3
3 1 4
4 4 2
5 4 1
注释
idcomments idusers text
1 1 asfd
2 2 safd
用户
idusers
1
2
3
4
例如,如果我是id#1用户,我就关注用户#2,#3,#4
我的页面会填充显示:
我不确定显示此内容的最佳方法是什么?我目前有多个函数一次查询表,我正在努力将数组合并在一起?或者我应该使用连接表?我现在正在尝试......
获取我正在关注的用户。
$feeds = new feed();
$meID = 1;
$query = "SELECT idusers FROM follow WHERE iduserse_follower = ?";
$users = $dbh -> prepare($query);
$users -> execute(array($meID));
while($following = $users -> fetch(PDO::FETCH_ASSOC)){
$follow = $following['idusers']; //This will get all of useres I'm following
$populate = $feeds->feed_all($follow); // from function
}
查询
class feed()
{
public function feed_all($idusers)
{
// SYNTAX HELP //////////////////////
$query = "SELECT
f.idusers_follower,
f.idusers,
l.iditem,
c.text
FROM follow f, users u
JOIN likes l
ON l.idusers = f.idusers
JOIN comment c
ON c.idusers = f.idusers
WHERE f.idusers_follower = ? AND f.idusers_follower = l.idusers AND f.idusers_follower = c.idusers AND f.idusers = u.idusers"
$pop = $dbh->prepare($query);
$pop ->execute($idusers);
// while loop to return value
while($row = $pop -> fetch(PDO::FETCH_ASSOC))
{
$feed_data[]=$row;
}
return $feed_data;
}
}
这就是我被困住的地方。 :(我甚至不确定我的声明是否合适?
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
我已编辑添加 idbusiness 现在,因为我正在关注#4,所以它也会出现#4跟随#1。
答案 0 :(得分:4)
您目前执行三个单独查询的方法与任何查询一样好;您可以使用UNION
将它们组合到一个结果集中,如果您希望按某个字段(例如活动时间戳)对组合结果进行排序和/或限制组合结果,这将非常有用:
SELECT idusers, 'likes' AS what, likes.iditem AS detail
FROM likes JOIN follow USING (idusers)
WHERE follow.idusers_follower = 1
UNION ALL
SELECT f1.idusers, 'follows', f2.idusers
FROM follow f1 JOIN follow f2 ON f1.idusers = f2.idusers_follower
WHERE f1.idusers_follower = 1
UNION ALL
SELECT idusers, 'commented', comment.text
FROM comment JOIN follow USING (idusers)
WHERE follow.idusers_follower = 1
在sqlfiddle上查看。