如何为make循环编写左连接

时间:2017-06-25 08:04:30

标签: php mysql

我想用left join语句在一个查询中编写此代码。目前我使用php for循环这个查询,但它不好,而且太慢了

该应用具有likedislike选项。我想要每个用户的数量

     public function getUserLikedCount($id) {
        $query = $this->db->query(
          "SELECT * FROM `users`, post, `like`
            WHERE users.id = post.post_user_id
            AND like.like_post_id = post.post_id
            AND users.id = ?
            AND post.post_is_active = 1", array($id)
        );
        return $query->num_rows();
    }

感谢

2 个答案:

答案 0 :(得分:1)

尝试使用它(我不知道你的表like结构):

$sql = 'SELECT u.id AS `user_id`
               COUNT(p.post_id) AS `liked_cnt` <-- or like.id ( if this field exists)
        FROM `post` AS p
        LEFT JOIN `users` AS u
          ON ( u.id = p.post_user_id )
        LEFT JOIN `like` AS l
          ON ( l.like_post_id = p.post_id )  
        WHERE  p.post_is_active = 1
              AND l.status = 1 <-- "liked"
        GROUP BY u.id ';

答案 1 :(得分:0)

Try this :  
  $query = $this->db->query(
              "SELECT * FROM `users` u
            LEFT  JOIN post p ON u.id = p.post_user_id AND u.id =?        
            LEFT  JOIN like l ON l.like_post_id = p.post_id AND p.post_is_active = 1
             ", array($id)