2012-05-06 70 views
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查詢工作正常,如果我只是想獲取對特定職位的所有意見,但我不知道如何限制要顯示的評論數。社交網絡的信息發表評論算法對MySQL

我試着把選擇放在左邊的連接中,並放上一些限制。

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

但它只顯示4條評論,其他帖子即使在數據庫中有評論也沒有評論顯示。我認爲它只能在評論表中檢索4條評論。

所以請任何想法如何解決這個問題,謝謝!

回答

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查詢

+0

謝謝@nvuono,但我得到這個錯誤該版本的MySQL還不支持「LIMIT& IN/ALL/ANY/SOME子查詢' –

+0

我試着在有限的SELECT查詢中重寫IN子句作爲另一個JOIN – nvuono

+0

它只顯示一個包含註釋的文章... –