我有一個從數據庫中提取帖子的SQL查詢。一切工作正常,但現在我需要按每個帖子的評論數量排序結果。評論是在一個單獨的表格上,他們有一個post_id列將其鏈接到該帖子。我需要根據評論表的數量來根據分片ID排序。我嘗試了一切,但每次嘗試添加一些內容到我的查詢時,它都會停止運行並將我的頁面留空。我需要幫助才能知道將其他JOIN語句放在哪裏。這是我的查詢:如何通過基於分片ID的另一個表的計數來排序SQL查詢的結果?
$union = "UNION ALL
(
SELECT DISTINCT wallposts.p_id,wallposts.is_profile_notes,wallposts.times_viewed,wallposts.columnTimesShared,
wallposts.marked,wallposts.secure_id,wallposts.reshared,wallposts.group_id,
wallposts.totaluploads,wallposts.WallUploadID,wallposts.type,
wallposts.value,wallposts.media,wallposts.youtube,wallposts.post_type,
wallposts.privacy,wallposts.tagedpersons,wallposts.with_friends_tagged,wallposts.emotion_head,wallposts.selected_emotion,wallposts.title,
wallposts.url,wallposts.description,wallposts.cur_image,
wallposts.uip,wallposts.likes,wallposts.userid,
wallposts.posted_by,wallposts.post as postdata,wallusers.*,
UNIX_TIMESTAMP() - wallposts.date_created AS TimeSpent,
PosterTable.mem_pic as posterPic, PosterTable.gender as posterGender,PosterTable.oauth_uid as poster_oauth_uid, PosterTable.username as posterUsername,
PosterTable.mem_fname as posterFname,PosterTable.work as posterWork,
PosterTable.mem_lname as posterLname,walllikes_track.id as PostLikeFound,wallposts.date_created
FROM
wallusers,wallusers as PosterTable, wallposts
LEFT JOIN walllikes_track
ON wallposts.p_id = walllikes_track.post_id AND walllikes_track.member_id = ".$user_id."
WHERE
wallusers.active = 1
AND
PosterTable.active = 1
AND
wallposts.group_id IN (".$groups.")
AND
wallposts.group_id != 0
AND
PosterTable.mem_id = wallposts.posted_by
AND
wallposts.marked < ".$this->flagNumber."
AND
wallusers.mem_id = wallposts.posted_by) ";
評論表被稱爲wallcomments,它有一個名爲post_id的列。我知道我需要使用JOIN和COUNT,但我不知道把它放在我現在的代碼中。
將一個額外的連接添加到子查詢中,該子查詢可以查找每個帖子的評論計數並使用它。我無法給出確切的答案,因爲缺少很多細節,而且您的查詢亂七八糟。 –
我應該在哪裏插入JOIN?這是我的困境。每當我對查詢進行任何更改時。它完全停止運行。 –
是的,因爲你的查詢非常龐大,難以理解,問題也是如此。下一次,通過展示您的問題的最小示例來提出更好的問題。沒有人可以重現您現在的查詢,因爲甚至沒有任何數據可用。 –