如何加入这3个表

时间:2014-02-04 01:06:14

标签: php mysql sql join mysqli

我已经完成了以下JOIN查询:

$stmt = $cxn->prepare('SELECT p.post_id, p.reply_to, p.parent_id, p.post_path, p.user_id, p.content, p.datetime, p.total_likes, p.total_replies, p.total_reposts, u.username, u.display_name FROM posts p LEFT JOIN users u ON p.user_id = u.user_id WHERE p.user_id IN (SELECT following_id FROM follows WHERE user_id = ?) AND p.removed != 1 ORDER BY p.datetime DESC LIMIT 26');
$stmt->bind_param('i', $user_info[0]);
$stmt->execute();

我有另一个查询,其唯一目的是检查行是否存在:

$stmt = $cxn->prepare('SELECT COUNT(like_id) FROM likes WHERE post_id = ? AND user_id = ?');
$stmt->bind_param('ii', $row['post_id'], $user_info[0]); // $row['post_id'] is the value of p.post_id from the first query
$stmt->execute();

如何将第二个查询加入第一个查询?我从未加入过三张桌子,所以我不确定这个程序。

感谢。

2 个答案:

答案 0 :(得分:0)

在查询中加入三个表就像加入两个表,除了......你加入三个。

基本上它会是这样的:

SELECT p.post_id (...), u.username (...), COUNT(l.like_id) AS nbOfLikes
    FROM posts p
    LEFT JOIN users u ON p.user_id = u.user_id
    LEFT JOIN likes l ON l.post_id = p.post_id AND l.user_id = u.user_id
    WHERE p.user_id IN
        (SELECT following_id
            FROM follows
            WHERE user_id = ?)
    AND p.removed != 1
    ORDER BY p.datetime DESC
    LIMIT 26;

- 实际上我认为UNION可能更适合您对likes表的需求。

答案 1 :(得分:0)

如果您总是将user_id填入表帖并且它是外键,请避免使用左连接语句,您可以使用join语句获得更好的性能。要连接3个或更多表,您只需添加连接语句:     选择         p.post_id         ,p.reply_to         ,p.parent_id         ,p.post_path         ,p.user_id         ,p.content         ,p.datetime         ,p.total_likes         ,p.total_replies         ,p.total_reposts         ,u.username         ,u.display_name     来自帖子p     JOIN用户u ON p.user_id = u.user_id WHERE p.user_id IN(SELECT following_id FROM如下     在TABLE_2.id = posts.TABLE_id上加入TABLE_2     JOIN TABLE_3 ON TABLE_3.id = posts.TABLE_id     ...     哪里         user_id =?)         AND p.removed!= 1     ORDER BY p.datetime DESC     限制26