$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查询工作正常,但我不知道如何限制要显示的评论数量。
我尝试将select放入其中一个左连接并设置一些限制。
LEFT JOIN (SELECT * FROM $comments_table LIMIT 4) d ON d.post_id_fk = c.post_id
但它只显示4条评论,即使数据库中有评论,其他帖子也没有显示评论。我认为它只能在评论表中检索4条评论。
所以请知道如何解决这个问题谢谢!
答案 0 :(得分: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查询