1

我有这些桌子;

user - contains user_id | username | fullname | email etcc
user_followers - contains follow_id| user_id | follower_id | date etcc
posts - contains post_id | user_id | post | post_date 

我正在尝试获取用户关注的用户和用户自己的帖子的所有帖子。

我试过了

$this->db->select('posts.*')->from('posts')
        ->join('user_followers', 'user_followers.user_id = posts.user_id', 'INNER')
        ->where('user_followers.follower_id', $user_id)->order_by('posts.post_date','desc');
    $query = $this->db->get(); 

但问题是,我无法从此查询中获取用户的帖子。我已经尝试了 or_where 等其他方法,并且我能够获取用户的帖子,只是数据增加了三倍:(有人可以帮我吗?非常感谢提前。

哦,在正常的Mysql中,它的;

SELECT  posts.*
FROM    posts
JOIN    user_followers
ON      user_followers.user_id = posts.user_id
WHERE   user_followers.follower_id = $user_id
ORDER BY
    posts.post_date DESC
4

3 回答 3

2

->where() supports passing any string to it and it will use it in the query, provided you pass a second and third parameter of NULL and FALSE respectively. This tells CI not to escape the query. E.g.

$where_query = "p.user_id = $user_id OR p.user_id IN (SELECT user_id FROM user_followers WHERE follower_id = $user_id)";
->where($where_query,NULL,FALSE);

Alternatively, you could check out this subquery library https://github.com/EllisLab/CodeIgniter/wiki/Subqueries

于 2012-11-22T11:10:42.870 回答
1
SELECT  p.*
FROM    (
        SELECT  user_id
        FROM    user_followers
        WHERE   follower_id = $user_id
        UNION ALL
        SELECT  $user_id
        ) uf
JOIN    posts p
ON      p.user_id = uf.user_id
于 2012-11-22T05:53:53.850 回答
0

为什么不是子选择?

select * from posts 
where user_id IN (
    select user_followers.follower_id 
        from user_followers 
        where user_followers.user_id=$user_id) 
    OR posts.user_id = $user_id;
于 2012-11-21T22:09:41.693 回答