取決於如果你只是想每PRODUCT_ID最近的評論,或者如果你想所有的意見,而只是由PRODUCT_ID分類,其中有最新評論該產品是第一個。
如果你想所有意見,由PRODUCT_ID,其中product_ids在最新評論的排序分組(即看到最新的時間戳順序如何提示產品是爲了(3,1,2 ):
product_id comment_timestamp
3 2012-03-13
3 2012-03-09
3 2012-03-01
1 2012-03-12
1 2012-01-01
2 2012-03-11
然後這裏是你如何能做到這一點 - 通過它才能找出每個產品的最新時間戳,加入該到你的主查詢和:
SELECT comments.products_products_id, products.name,
products.minilocation, products.users_user_id,
comments.comment, comment_id, comments.time_stamp,
users.username, users.miniavatar
FROM products
-- NEW JOIN:
INNER JOIN (SELECT product_id, MAX(time_stamp) as latest
FROM comments
GROUP BY product_id) latest
ON latest.product_id = products.product_id
-- as before.
INNER JOIN comments ON comments.products_products_id = products.products_id
INNER JOIN users ON users.user_id = comments.products_users_user_id
-- NEW SORT:
ORDER BY latest.latest DESC, comments.time_stamp DESC
加入的新表格是最大值(即最新的)每個產品ID的時間戳。 這將在單個產品ID中相同。
我們是用這種第一(通過最新的評論時間戳排序),並然後內的每個產品編號排序個人評論時間戳。
如果你想每PRODUCT_ID最近的評論,即
product_id comment_timestamp
3 2012-03-13
1 2012-03-12
2 2012-03-11
然後使用:
SELECT comments.products_products_id, products.name,
products.minilocation, products.users_user_id,
comments.comment, comment_id, comments.time_stamp,
users.username, users.miniavatar
FROM comments
-- NEW SELF-JOIN
LEFT JOIN comments c2 ON comments.products_products_id = c2.products_products_id
AND comments.time_stamp < c2.time_stamp
INNER JOIN products ON comments.products_products_id = products.products_id
INNER JOIN users ON users.user_id = comments.products_users_user_id
-- new condition
WHERE c2.time_stamp IS NULL
ORDER BY comments.time_stamp DESC
這種類型的查詢被稱爲 「每組最大的N」,和你基本上每個產品ID都加入您的COMMENTS表格以內。你也加入它,使得一個表的time_stamps小於另一個。 WHERE
條件選擇行,使得product_id沒有更大的時間戳,即最新的評論。
Is comments.products_products_id actually comments.products_id? – 2012-03-13 00:58:06
所以你想要通過最新的評論來訂購,確保一件物品的所有評論都粘在一起? – 2012-03-13 00:59:09
你所有的ID都是正確的。基本上只是想把最新評論活動的產品放在最前面。不要任何重複的產品ID – Anonymous 2012-03-13 01:02:26