0
$query = $this->db->query("SELECT a.fullname AS fullname_post , a.picture, a.user_id, c.post_id, c.date_posted, c.total_comments, c.content AS post, UNIX_TIMESTAMP() - c.date_posted AS p_time_spent, c.photo, d.comment_id, d.comment_date, d.content AS comments, UNIX_TIMESTAMP() - d.comment_date AS c_time_spent, d.post_id_fk, e.fullname AS fullname_comments 
     from $post_table c
     LEFT JOIN $comments_table d ON d.post_id_fk = c.post_id
     LEFT JOIN $user_table a on a.user_id=c.post_owner_fk
     LEFT JOIN $user_table e on e.user_id=d.comment_owner_id_fk
     LEFT JOIN $contact_table f on f.user_id_fk='$user_id' OR f.user_id_fk2='$user_id'
     WHERE c.post_owner_fk = '$user_id' OR c.post_owner_fk = f.friend_id_fk OR c.post_owner_fk = f.friend_id_fk2
     ORDER BY c.post_id DESC, d.comment_id ASC"
    );

如果我只想检索对特定帖子的所有评论,但我不知道如何限制要显示的评论数量,上面的 mysql 查询可以正常工作。

我尝试将选择放在左连接之一中并设置一些限制。

LEFT JOIN (SELECT * FROM $comments_table LIMIT 4) d ON d.post_id_fk = c.post_id

但它只显示 4 条评论,即使数据库中有评论,其他帖子也没有显示评论。我认为它只检索评论表中的 4 条评论。

所以请任何想法如何解决这个问题谢谢!

4

1 回答 1

0

你可以在 MySQL 中尝试这样的事情吗?

SELECT a.fullname AS fullname_post , a.picture, a.user_id, c.post_id, c.date_posted,
   c.total_comments, c.content AS post, UNIX_TIMESTAMP() - c.date_posted AS p_time_spent,
   c.photo, d.comment_id, d.comment_date, d.content AS comments, 
   UNIX_TIMESTAMP() - d.comment_date AS c_time_spent, d.post_id_fk, 
   e.fullname AS fullname_comments  
     FROM $post_table c 
     LEFT JOIN $comments_table d ON d.post_id_fk = c.post_id 
      LEFT JOIN
           (SELECT tmpc.post_id_fk 
                 FROM $comments_table tmpc 
                 WHERE tmpc.post_id_fk = c.post_id 
                 ORDER BY tmpc.comment_date DESC
                 LIMIT 4) as climited
            ON climited.post_id_fk = c.post_id                 
     LEFT JOIN $user_table a on a.user_id=c.post_owner_fk 
     LEFT JOIN $user_table e on e.user_id=d.comment_owner_id_fk 
     LEFT JOIN $contact_table f on f.user_id_fk='$user_id' 
               OR f.user_id_fk2='$user_id' 
     WHERE c.post_owner_fk = '$user_id' 
           OR c.post_owner_fk = f.friend_id_fk 
           OR c.post_owner_fk = f.friend_id_fk2 
     ORDER BY c.post_id DESC, d.comment_id ASC

编辑: 将 IN 子句替换为“有限”SELECT 查询的另一个连接

于 2012-05-06T07:24:39.090 回答