我正在尝试从4个表中提取数据。当我从MySQL表的3(user_table,posts,followers)中提取数据时,数据被检索得很好。当我试图从第4个表(post_likes)中拉出特定列时,我遇到了问题。所有数据都根本不显示。
这是数据库结构:
user_table:user_id, username, name
帖子:post_id, body, user_id, likes
粉丝:follower_id, user_id, follower_id
post_likes:likes_id, post_id, user_id
连接脚本:
class DB {
private static function connect() {
$pdo = new PDO ('mysql:host=localhost;dbname=test;charset=utf8','root','');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $pdo;
}
public static function query($query, $params = array()) {
$statement = self::connect()->prepare($query);
$statement->execute($params);
if (explode(' ', $query)[0] == 'SELECT') {
$data = $statement->fetchAll();
return $data;
}
}
}
脚本可以从3个表中提取数据:
$posts = DB::query('SELECT posts.post_id, posts.body, posts.likes,
users_table.username, users_table.name FROM users_table, posts, followers
WHERE posts.user_id = followers.user_id
AND users_table.user_id = posts.user_id
AND follower_id = :userid
ORDER BY posts.posted_at DESC', array(':userid'=>$userid));
脚本无法从4个表中提取数据:
$posts = DB::query('SELECT posts.post_id, posts.body, post_likes.post_id,
post_likes.user_id, posts.likes, users_table.username, users_table.name
FROM users_table, posts, followers, post_likes
WHERE posts.user_id = followers.user_id
AND users_table.user_id = posts.user_id
AND follower_id = :userid
ORDER BY posts.posted_at DESC', array(':userid'=>$userid));
我可以为此提供任何帮助吗?感谢名单
答案 0 :(得分:1)
4表查询失败的原因是将 post_likes 表添加到查询中,但没有提供从当前数据集到post_likes表的任何类型的链接。
请注意所有where子句将表格链接在一起。您的 post_likes 表格中没有where子句链接。
我的asummption是你需要更新你的WHERE子句:
WHERE posts.user_id = followers.user_id
AND post_likes.post_id = posts.post_id //Link post_likes here
AND users_table.user_id = posts.user_id
AND follower_id = :userid
编辑:正如大卫所说,你应该使用实际的JOIN命令。
答案 1 :(得分:0)
正确的做法是:
SELECT
posts.post_id, posts.body, post_likes.post_id,
post_likes.user_id, posts.likes, users_table.username, users_table.name
FROM
users_table
inner join posts on users_table.user_id = posts.user_id
inner join followers on posts.user_id = followers.user_id
inner join post_likes on post_likes.id = <your condition>
WHERE
follower_id = :userid
ORDER BY posts.posted_at DESC
我们假设follower_id列只存在于表中的1个,否则会抛出歧义错误