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クエリは、特定の投稿へのすべてのコメントを取得したいだけで、表示するコメントの数を制限する方法がわからない場合は正常に機能します。

左側の結合の1つにselectを入れて、制限を設けようとしています。

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 に答える